#!/usr/bin/env python
# -*- coding: utf-8 -*-

# package  : Inventorius - PyGTK Custom Inventory System
# version  : $Id$
# copyright: Copyright (c) 2010 Bertrand Kintanar <bertrand.kintanar@gmail.com>
# license  : http://opensource.org/licenses/gpl-3.0.html
# url      : http://c0dejunk1e.tumblr.com/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# If you find any bugs or have any suggestions email: bertrand.kintanar@gmail.com
#
# Inventorius needs the following to function properly:
#   python >= 2.5.1, gtk >= 2.14.1, pygtk >= 2.12.2, 
#   sqlite >= 2.3.5, sqlalchemy >= 0.5.0

__version__ = "$Rev$"
# $HeadURL$

_ = lambda x : x

from config import *
from config import __appversion__

try:
    
    import base64
    import calendar
    import datetime
    import gettext
    import locale
    import os
    import platform
    import re
    import sys
    
except ImportError, e:
    
    # Do not translate
    print "Import error %s cannot start:" % APP_NAME, e
    
    sys.exit(1)
    
    
try:
    
    import gobject
    import pygtk
    pygtk.require20()
    
    import gtk
    
    try:
        
        assert gtk.ver >= (2, 14, 1)
        
    except AssertionError:
        
        # Do not translate
        print "%s requires GTK+ 2.14.1 or higher, but %s was found" \
              % (APP_NAME, gtk.ver)
        
        sys.exit(1)
        
    if DEBUG:
        
        # Do not translate
        print "Checking pygtk >= 2.0.......... Found"
        print "Checking gtk+  >= 2.14.1....... Found"
        
except ImportError, e:

    # Do not translate
    print "Import error %s cannot start:" % APP_NAME, e
    
    sys.exit(1)
    
from sql import *
from datepicker import CalendarEntry

session = checkDatabase()

"""Column IDs"""
COL_OBJECT      = 0
COL_OBJECT_TYPE = 1
COL_CODE        = 2
COL_TITLE       = 3
COL_NAME        = 3
COL_GENRES      = 4
COL_NUMBER      = 4
COL_ADDRESS     = 5
COL_TYPE        = 5
COL_CITY        = 6
COL_PROV        = 7
COL_ZIP         = 8
COL_COUNTRY     = 9

class TVColumn(object):
    """
    This is a class that represents a column in the todo tree.
    It is simply a helper class that makes it easier to inialize the
    tree.
    """
    
    def __init__(self, ID, type, name, pos, visible=False, cellrenderer=None):
        """
        @param ID - int - The Columns ID
        @param type - int  - A gobject.TYPE_ for the gtk.TreeStore
        @param name - string - The name of the column
        @param pos - int - The index of the column.
        @param visible - boolean - Is the column visible or not?
        @param cellrenderer - gtk.CellRenderer - a constructor function
        for the column
        """
        self.ID = ID
        self.type = type
        self.name = name
        self.pos = pos
        self.visible = visible
        self.cellrenderer = cellrenderer
        self.colour = 0
        
    def __str__(self):
        
        return "<TVColumn object: ID = %s type = %s name = %s pos = %d visible = %s cellrenderer = %s>" % (self.ID, self.type, self.name, self.pos, self.visible, self.cellrenderer)
        
class Inventorius(object):
    
    def __init__(self):
        
        if DEBUG:
            
            print _("Initializing UI with gtk.Builder")
            
        #Get the local path
        self.local_path = os.path.realpath(os.path.dirname(sys.argv[0]))
        #Translation stuff
        self.initialize_translation()
        
        #Set the gtk.Builder from xml
        self.builder = gtk.Builder()
        self.builder.add_from_file(os.path.join(self.local_path, "ui", "ui.xml"))
        
        #Get the Main Window Object
        self.main_window = self.builder.get_object("mainWindow")
        
        if LOGIN:
            
            self.security()
            
        #Initialize some widgets
        self.initialize_widgets()
        
        self.main_window.set_title(APP_NAME + " " + __appversion__ + " r" + __version__.split(" ")[1]) 
        
        #Connect with yourself
        self.builder.connect_signals(self)
        
        self.reCuEntry.grab_focus()
        self.main_window.show_all()
        
        if len(self.current_permissions['category_access']) <= 1:
        
            self.inCategoryCombobox.hide()
            
        self.reButton.hide()
        self.daButton.hide()
        
        self.notebook.set_current_page(6)
        
        self.main_window.maximize()
        
    #***************************************************************************
    # Initializations
    #***************************************************************************
    def initialize_widgets(self):
        
        self.notebook       = self.builder.get_object("notebook")
        
        self.reNotebook     = self.builder.get_object("reNotebook")
        self.reCuEntry      = self.builder.get_object("reCuEntry")
        self.reInEntry      = self.builder.get_object("reInEntry")
        self.reInAlertLabel = self.builder.get_object("reInAlertLabel")
        
        self.inEntry = self.builder.get_object("inEntry")
        self.inCategoryCombobox = self.builder.get_object("inCategoryCombobox")
        self.inFindButton = self.builder.get_object("inFindButton")
        
        self.inAddButton = self.builder.get_object("inAddButton")
        self.eqAddButton = self.builder.get_object("eqAddButton")
        self.exAddButton = self.builder.get_object("exAddButton")
        self.maUsUserModifyButton = self.builder.get_object("maUsUserModifyButton")
        self.exRepairAddButton = self.builder.get_object("exRepairAddButton")
        self.exSalaryAddButton = self.builder.get_object("exSalaryAddButton")

        
        self.root_window = self.main_window.get_root_window()
        
        self.create_buttonImages()
        self.create_statusbar()
        self.set_permissions()
        self.create_warningDialog()
        self.create_aboutDialog()
        #self.create_cuAddEditDialog()
        self.create_itemAddEditDialog()
        self.create_eqAddEditDialog()
        self.create_reAddEditDialog()
        self.create_maUserManagementDialog()
        self.create_userAddEditDialog()
        self.create_warehouseAddEditDialog()
        self.create_operatorAddEditDialog()
        self.create_unitAddEditDialog()
        self.create_expenseAddEditDialog()
        self.create_reportDetailsDialog()
        self.populate_eqListstore()
        self.populate_inListstore()
        
        if len(self.current_permissions['category_access']) > 1:
            
            self.inCategoryListstore = gtk.ListStore(str)
            cellRenderer = gtk.CellRendererText()
            
            self.inCategoryListstore.append([_("All Categories")])
            for instance in session.query(Category).filter(Category.id.in_(self.current_permissions['category_access'])).order_by(Category.name):
                
                self.inCategoryListstore.append([instance.name])
                
            self.inCategoryCombobox.pack_start(cellRenderer, True)
            self.inCategoryCombobox.add_attribute(cellRenderer, "text", 0)
            self.inCategoryCombobox.set_model(self.inCategoryListstore)
            self.inCategoryCombobox.set_active(0)
        
        else:
            
            self.inCategoryCombobox.hide()
        
    def initialize_translation(self):
        """This function initializes the possible translations"""
        
        global _
        # Init the list of languages to support
        langs = []
        
        #Check the default locale
        lc, encoding = locale.getdefaultlocale()
        
        if (lc):
            #If we have a default, it's the first in the list
            langs = [lc]
            
        # Now lets get all of the supported languages on the system
        language = os.environ.get("LANGUAGE", None)
        
        if (language):
            """
            language comes back something like en_CA:en_US:en_GB:en
            on linuxy systems, on Win32 it's nothing, so we need to
            split it up into a list
            """
            
            langs += language.split(":")
            
        """
        Now add on to the back of the list the translations that we
        know that we have, our defaults
        """
        
        langs += ["tl_PH", "en_PH"]
        
        """
        Now langs is a list of all of the languages that we are going
        to try to use.  First we check the default, then what the system
        told us, and finally the 'known' list
        """
        
        gettext.bindtextdomain('inventorius', os.path.join(self.local_path, "locale"))
        gettext.textdomain('inventorius')
        
        # Get the language to use
        self.lang = gettext.translation(
            'inventorius', os.path.join(self.local_path, "locale"), 
            languages=langs, fallback = True
        )
        
        """
        Install the language, map _() (which we marked our
        strings to translate with) to self.lang.gettext() which will
        translate them.
        """
        gettext.install('inventorius', os.path.join(self.local_path, "locale"))
        
        _ = self.lang.gettext
        
    #***************************************************************************
    # Create Widgets
    #***************************************************************************
    def create_buttonImages(self):
        
        self.reButton = self.builder.get_object("reButton")
        self.inButton = self.builder.get_object("inButton")
        self.exButton = self.builder.get_object("exButton")
        self.trButton = self.builder.get_object("trButton")
        self.rpButton = self.builder.get_object("rpButton")
        self.daButton = self.builder.get_object("daButton")
        self.maButton = self.builder.get_object("maButton")
        
        reImageBox = self.add_image(self, "rentals.png", _("_Rentals"))
        inImageBox = self.add_image(self, "inventory.png", _("_Inventory"))
        exImageBox = self.add_image(self, "expenses.png", _("_Expenses"))
        trImageBox = self.add_image(self, "equipment.png", _("E_quipment"))
        rpImageBox = self.add_image(self, "reports.png", _("Rep_orts"))
        maImageBox = self.add_image(self, "maintenance.png", _("_Maintenance"))
        daImageBox = self.add_image(self, "dayend.png", _("_Day-End"))
        
        self.reButton.set_image(reImageBox)
        self.inButton.set_image(inImageBox)
        self.exButton.set_image(exImageBox)
        self.trButton.set_image(trImageBox)
        self.rpButton.set_image(rpImageBox)
        self.maButton.set_image(maImageBox)
        self.daButton.set_image(daImageBox)
        
        reImageBox.show()
        inImageBox.show()
        exImageBox.show()
        trImageBox.show()
        rpImageBox.show()
        maImageBox.show()
        daImageBox.show()
        
    def create_statusbar(self):
        
        self.statusbar = self.builder.get_object("statusbar")
        
        self.context_id = self.statusbar.get_context_id("POSvrSys")
        self.m_context_id = self.statusbar.get_context_id("Movie")
        
        self.c_context_id = self.context_id
        
        text = _("Welcome to") 
        
        self.statusbar.push(self.context_id, text + " %s %s" % (APP_NAME, __appversion__))
        
    def create_inListstore(self):
        
        """
        Creates and populates the inListstore. inListstore contains list of 
        movies in the inventory. It displays it in a table form displaying 
        the id, title, genres, and the director of a given movie.
        """
        
        self.inListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(2, gobject.TYPE_INT, _("Code"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Items / Particulars"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Stocks"), 4, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.inTreeview = self.builder.get_object("inTreeview")
        #Make it so that the colours of each row can alternate
        self.inTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.inListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                # Set the column to expand if it is the column Title
                column.set_expand(item_column.name == _("Items / Particulars"))
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.inTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.inListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.inTreeview.set_model(self.inListstore)
        
    def create_eqListstore(self):
        
        """
        Creates and populates the inListstore. inListstore contains list of 
        movies in the inventory. It displays it in a table form displaying 
        the id, title, genres, and the director of a given movie.
        """
        
        self.eqListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(2, gobject.TYPE_STRING, _("#"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Type"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Make"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_STRING, _("Engine #"), 5, True, gtk.CellRendererText())
            , TVColumn(6, gobject.TYPE_STRING, _("Plate #"), 6, True, gtk.CellRendererText())
            , TVColumn(7, gobject.TYPE_STRING, _("Chassis #"), 7, True, gtk.CellRendererText())
            , TVColumn(8, gobject.TYPE_STRING, _("Rental Rate / Unit"), 8, True, gtk.CellRendererText())
            , TVColumn(9, gobject.TYPE_STRING, _("LTO"), 9, True, gtk.CellRendererText())
            , TVColumn(10, gobject.TYPE_STRING, _("Availability"), 10, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.eqTreeview = self.builder.get_object("eqTreeview")
        #Make it so that the colours of each row can alternate
        self.eqTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.eqListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                # Set the column to expand if it is the column Title
                column.set_expand(item_column.name == _("#"))
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.eqTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.eqListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.eqTreeview.set_model(self.eqListstore)
        
    def create_reListstore(self):
        
        """
        Creates and populates the inListstore. inListstore contains list of 
        movies in the inventory. It displays it in a table form displaying 
        the id, title, genres, and the director of a given movie.
        """
        
        self.reListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("#"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Type"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Expenses"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Income"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_STRING, _("Net"), 5, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.reTreeview = self.builder.get_object("reTreeview")
        #Make it so that the colours of each row can alternate
        self.reTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.reListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                # Set the column to expand if it is the column Title
                column.set_expand(item_column.name == _("#"))
                
                if item_column.pos > 2:
                    
                    column.set_alignment(1)
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.reTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.reListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.reTreeview.set_model(self.reListstore)
        
    def create_inStockListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.inStockListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date / Time"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Stocks"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Unit Price"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Warehouse"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_STRING, _("Description"), 5, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.stocksTreeview = self.builder.get_object("stocksTreeview")
        #Make it so that the colours of each row can alternate
        self.stocksTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.inStockListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.stocksTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.inStockListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.stocksTreeview.set_model(self.inStockListstore)
        
    def create_maUsUserListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.maUsUserListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_INT, _("ID"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Type"), 2, False, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Username"), 3, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.maUsersTreeview = self.builder.get_object("maUsersTreeview")
        #Make it so that the colours of each row can alternate
        self.maUsersTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.maUsUserListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.maUsersTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.maUsUserListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.maUsersTreeview.set_model(self.maUsUserListstore)
        self.populate_maUsUserListstore()
        
    def create_maWarehousesListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.maWarehousesListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_INT, _("ID"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Name"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Description"), 3, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.maWarehousesTreeview = self.builder.get_object("maWarehousesTreeview")
        #Make it so that the colours of each row can alternate
        self.maWarehousesTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.maWarehousesListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.maWarehousesTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.maWarehousesListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.maWarehousesTreeview.set_model(self.maWarehousesListstore)
        self.populate_maWarehousesListstore()
        
    def create_maOperatorsListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.maOperatorsListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_INT, _("ID"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Last Name"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("First Name"), 3, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.maOperatorsTreeview = self.builder.get_object("maOperatorsTreeview")
        #Make it so that the colours of each row can alternate
        self.maOperatorsTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.maOperatorsListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.maOperatorsTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.maOperatorsListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.maOperatorsTreeview.set_model(self.maOperatorsListstore)
        self.populate_maOperatorsListstore()
        
    def create_maUnitsListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.maUnitsListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_INT, _("ID"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Name"), 2, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.maUnitsTreeview = self.builder.get_object("maUnitsTreeview")
        #Make it so that the colours of each row can alternate
        self.maUnitsTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.maUnitsListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.maUnitsTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.maUnitsListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.maUnitsTreeview.set_model(self.maUnitsListstore)
        self.populate_maUnitsListstore()
        
    def create_exItListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.exItListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Type"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_INT, _("Quantity"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Unit"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_INT, _("Rate / Unit"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_INT, _("Amount"), 5, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.exItemTreeview = self.builder.get_object("exItemTreeview")
        #Make it so that the colours of each row can alternate
        self.exItemTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.exItListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.exItemTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.exItListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.exItemTreeview.set_model(self.exItListstore)
        
    def create_exListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.exListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("PO Number"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Equipment Number"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Amount"), 4, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.exTreeview = self.builder.get_object("exTreeview")
        #Make it so that the colours of each row can alternate
        self.exTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.exListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                if item_column.name == _("Equipment Number"):
                    
                    column.set_expand(True)
                    
                if item_column.name == _("Amount"):
                    
                    column.set_alignment(1)
                    
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.exTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.exListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.exTreeview.set_model(self.exListstore)
        
    def create_rePartsListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.rePartsListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("PO Number"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Item"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("QTY"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_STRING, _("Unit"), 5, True, gtk.CellRendererText())
            , TVColumn(6, gobject.TYPE_STRING, _("Rate / Unit"), 6, True, gtk.CellRendererText())
            , TVColumn(7, gobject.TYPE_STRING, _("Amount"), 7, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.rePartsTreeview = self.builder.get_object("rePartsTreeview")
        #Make it so that the colours of each row can alternate
        self.rePartsTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.rePartsListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                if item_column.name == _("Equipment Number"):
                    
                    column.set_expand(True)
                    
                if item_column.pos > 3:
                    
                    column.set_alignment(1)
                    
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.rePartsTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.rePartsListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.rePartsTreeview.set_model(self.rePartsListstore)
        
    def create_reFuelListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.reFuelListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("PO Number"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Item"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("QTY"), 4, True, gtk.CellRendererText())
            , TVColumn(5, gobject.TYPE_STRING, _("Unit"), 5, True, gtk.CellRendererText())
            , TVColumn(6, gobject.TYPE_STRING, _("Rate / Unit"), 6, True, gtk.CellRendererText())
            , TVColumn(7, gobject.TYPE_STRING, _("Amount"), 7, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.reFuelTreeview = self.builder.get_object("reFuelTreeview")
        #Make it so that the colours of each row can alternate
        self.reFuelTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.reFuelListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                if item_column.name == _("Equipment Number"):
                    
                    column.set_expand(True)
                    
                if item_column.pos > 3:
                    
                    column.set_alignment(1)
                    
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.reFuelTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.reFuelListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.reFuelTreeview.set_model(self.reFuelListstore)
        
    def create_reRepairListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.reRepairListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Service Provider"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Scope of Work"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Labor Charge"), 4, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.reRepairTreeview = self.builder.get_object("reRepairTreeview")
        #Make it so that the colours of each row can alternate
        self.reRepairTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.reRepairListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                if item_column.name == _("Labor Charge"):
                    
                    column.set_expand(True)
                    
                if item_column.pos > 3:
                    
                    column.set_alignment(1)
                    
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.reRepairTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.reRepairListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.reRepairTreeview.set_model(self.reRepairListstore)
        
    def create_reSalaryListstore(self):
        
        """
        Creates and populates the inStockListstore.
        """
        
        self.reSalaryListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(1, gobject.TYPE_STRING, _("Date"), 1, True, gtk.CellRendererText())
            , TVColumn(2, gobject.TYPE_STRING, _("Operator"), 2, True, gtk.CellRendererText())
            , TVColumn(3, gobject.TYPE_STRING, _("Remarks"), 3, True, gtk.CellRendererText())
            , TVColumn(4, gobject.TYPE_STRING, _("Amount"), 4, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        self.__column_dict = {} #For easy access later on
        
        #Get the treeView from the widget Tree
        self.reSalaryTreeview = self.builder.get_object("reSalaryTreeview")
        #Make it so that the colours of each row can alternate
        self.reSalaryTreeview.set_rules_hint(True)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.reSalaryListstore_columns:
            #Add the column to the column dict
            self.__column_dict[item_column.ID] = item_column
            #Save the type for gtk.TreeStore creation
            tree_type_list.append(item_column.type)
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(item_column.name
                    , item_column.cellrenderer
                    , text=item_column.pos)
                if item_column.name == _("Labor Charge"):
                    
                    column.set_expand(True)
                    
                if item_column.pos > 3:
                    
                    column.set_alignment(1)
                    
                column.set_resizable(False)
                column.set_sort_column_id(item_column.pos)
                self.reSalaryTreeview.append_column(column)
                
        #Create the gtk.TreeStore Model to use with the inTreeview
        self.reSalaryListstore = gtk.ListStore(*tree_type_list)
        #Attache the model to the treeView
        self.reSalaryTreeview.set_model(self.reSalaryListstore)
        
    def create_userWarehouseAddEditListstore(self):
        
        self.userWarehouseListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_CODE, gobject.TYPE_STRING, _("Name"), 2, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        __column_dict  = {} #For easy access later on
        
        for item_column in self.userWarehouseListstore_columns:
            
            tree_type_list.append(item_column.type)
            
        #Save the type for gtk.TreeStore creation
        self.userWarehouseAddEditListstore = gtk.ListStore(*tree_type_list)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.userWarehouseListstore_columns:
            #Add the column to the column dict
            __column_dict[item_column.ID] = item_column
            
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(
                    item_column.name, 
                    item_column.cellrenderer, 
                    text=item_column.pos
                )
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.userWarehouseTreeview.append_column(column)
                
        self.userWarehouseAddEditListstore.set_name("userWarehouseAddEditListstore")
        self.userWarehouseTreeview.set_model(self.userWarehouseAddEditListstore)
        #self.inGenresTreeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        
    def create_userCategoryAddEditListstore(self):
        
        self.userCategoryListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_CODE, gobject.TYPE_STRING, _("Name"), 2, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        __column_dict  = {} #For easy access later on
        
        for item_column in self.userCategoryListstore_columns:
            
            tree_type_list.append(item_column.type)
            
        #Save the type for gtk.TreeStore creation
        self.userCategoryAddEditListstore = gtk.ListStore(*tree_type_list)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.userCategoryListstore_columns:
            #Add the column to the column dict
            __column_dict[item_column.ID] = item_column
            
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(
                    item_column.name, 
                    item_column.cellrenderer, 
                    text=item_column.pos
                )
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.userCategoryTreeview.append_column(column)
                
        self.userCategoryAddEditListstore.set_name("userCategoryAddEditListstore")
        self.userCategoryTreeview.set_model(self.userCategoryAddEditListstore)
        #self.inGenresTreeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        
    def create_inWriterAddEditListstore(self):
        
        self.inWritersListstore_columns = [
            TVColumn(COL_OBJECT, gobject.TYPE_PYOBJECT, "object", 0)
            , TVColumn(COL_OBJECT_TYPE, gobject.TYPE_INT, "object_type", 1)
            , TVColumn(COL_CODE, gobject.TYPE_STRING, _("Full Name"), 2, True, gtk.CellRendererText())
        ]
        
        """Called when we want to initialize the tree.
        """
        tree_type_list = [] #For creating the TreeStore
        __column_dict  = {} #For easy access later on
        
        for item_column in self.inWritersListstore_columns:
            
            tree_type_list.append(item_column.type)
            
        #Save the type for gtk.TreeStore creation
        self.inWritersAddEditListstore = gtk.ListStore(*tree_type_list)
        
        # Loop through the columns and initialize the Tree
        for item_column in self.inWritersListstore_columns:
            #Add the column to the column dict
            __column_dict[item_column.ID] = item_column
            
            #is it visible?
            if (item_column.visible):
                #Create the Column
                column = gtk.TreeViewColumn(
                    item_column.name, 
                    item_column.cellrenderer, 
                    text=item_column.pos
                )
                
                column.set_resizable(True)
                column.set_sort_column_id(item_column.pos)
                self.inWritersTreeview.append_column(column)
                
        self.inWritersAddEditListstore.set_name("inWritersAddEditListstore")
        self.inWritersTreeview.set_model(self.inWritersAddEditListstore)
        #self.inGenresTreeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        
    def create_warningDialog(self):
        
        self.warningMessageDialog = self.builder.get_object("warningMessageDialog")
        self.warningMessageCancelButton = self.builder.get_object("warningMessageCancelButton")
        self.warningMessageDeleteButton = self.builder.get_object("warningMessageDeleteButton")
        
    def create_aboutDialog(self):
        
        def url_hook(dialog, url):
        
            open_url_in_browser(url)
            
        gtk.about_dialog_set_url_hook(url_hook)
        
        #Get the actual dialog widget
        self.aboutDialog = self.builder.get_object("aboutDialog")
        #self.aboutDialog.set_icon()
        self.aboutDialog.set_version(__appversion__ + " r" + __version__.split(" ")[1])
        
        if DEBUG:
            
            print _("   Creating aboutDialog........ Done")
            
    def create_itemAddEditDialog(self):
        
        self.create_inListstore()
        self.create_inStockListstore()
        
        self.itemAddEditDialog = self.builder.get_object("itemAddEditDialog")
        
        self.itemNameEntry = self.builder.get_object("itemNameEntry")
        self.itemUnitCombobox = self.builder.get_object("itemUnitCombobox")
        self.itemCategoryCombobox = self.builder.get_object("itemCategoryCombobox")
        
        self.itemNameLabel = self.builder.get_object("itemNameLabel")
        self.itemUnitLabel = self.builder.get_object("itemUnitLabel")
        self.itemCategoryLabel = self.builder.get_object("itemCategoryLabel")
        
        self.itemUnitListstore = gtk.ListStore(str)
        self.itemCategoryListstore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.populate_itemUnitListstore()
            
        self.itemUnitCombobox.pack_start(cellRenderer, True)
        self.itemUnitCombobox.add_attribute(cellRenderer, "text", 0)
        self.itemUnitCombobox.set_model(self.itemUnitListstore)
        self.itemUnitCombobox.set_active(0)
        
        self.itemCategoryListstore.append([_("Select one")])
        for instance in session.query(Category).filter(Category.id.in_(self.current_permissions['category_access'])).order_by(Category.name):
            
            self.itemCategoryListstore.append([instance.name])
            
        self.itemCategoryCombobox.pack_start(cellRenderer, True)
        self.itemCategoryCombobox.add_attribute(cellRenderer, "text", 0)
        self.itemCategoryCombobox.set_model(self.itemCategoryListstore)
        self.itemCategoryCombobox.set_active(0)
        
        self.itemWidgets = \
            [
                [self.itemNameEntry, self.itemNameLabel, _("_Name:"), True],
                [self.itemUnitCombobox, self.itemUnitLabel, _("_Unit:"), True],
                [self.itemCategoryCombobox, self.itemCategoryLabel, _("Ca_tegory:"), True],
            ]
        
        ## Add Stock Dialog
        self.stockAddDialog = self.builder.get_object("stockAddDialog")
        
        self.stockPrefixLabel = self.builder.get_object("stockPrefixLabel")
        self.stockPrefixLabel.set_text(PREFIX)
        
        self.stockWarehouseLabel = self.builder.get_object("stockWarehouseLabel")
        self.stockStockLabel = self.builder.get_object("stockStockLabel")
        self.stockUnitPriceLabel = self.builder.get_object("stockUnitPriceLabel")
        self.stockDescriptionLabel = self.builder.get_object("stockDescriptionLabel")
        self.stockStockSpinButton = self.builder.get_object("stockStockSpinButton")
        self.stockUnitPriceSpinButton = self.builder.get_object("stockUnitPriceSpinButton")
        self.stockWarehouseCombobox = self.builder.get_object("stockWarehouseCombobox")
        self.stockDescriptionEntry = self.builder.get_object("stockDescriptionEntry")
        
        self.stockWarehouseListstore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.stockWarehouseListstore.append([_("Select one")])
        for instance in session.query(Warehouse).filter(Warehouse.id.in_(self.current_permissions['warehouse_access'])).order_by(Warehouse.name):
            
            self.stockWarehouseListstore.append([instance.name])
            
        self.stockWarehouseCombobox.pack_start(cellRenderer, True)
        self.stockWarehouseCombobox.add_attribute(cellRenderer, "text", 0)
        self.stockWarehouseCombobox.set_model(self.stockWarehouseListstore)
        self.stockWarehouseCombobox.set_active(0)
        
        self.stockWidgets = \
            [
                [self.stockWarehouseCombobox, self.stockWarehouseLabel, _("_Warehouse:"), True],
                [self.stockDescriptionEntry, self.stockDescriptionLabel, _("_Description:"), True],
                [self.stockStockSpinButton, self.stockStockLabel, _("_Number of Stock:"), True],
                [self.stockUnitPriceSpinButton, self.stockUnitPriceLabel, _("_Unit Price:"), True],
            ]
        
        self.stockStockSpinButton.set_range(0, 10000000)
        self.stockUnitPriceSpinButton.set_range(0.00, 9999999999.00)
        self.stockStockSpinButton.set_increments(1, 1)
        self.stockUnitPriceSpinButton.set_increments(1, 1)
        
        if DEBUG:
            
            print _("   Creating itemAddEditDialog.. Done")
        
    def create_reAddEditDialog(self):
        
        self.create_reListstore()
        
        self.populate_reListstore()
        
    def create_eqAddEditDialog(self):
        
        self.create_eqListstore()
        
        self.eqAddEditDialog = self.builder.get_object("eqAddEditDialog")
        self.eqAddEditNotebook = self.builder.get_object("eqAddEditNotebook")
        self.eqStatusTable = self.builder.get_object("eqStatusTable")
        
        self.eqEntry                   = self.builder.get_object("eqEntry")
        self.eqFindButton              = self.builder.get_object("eqFindButton")
        
        self.eqEquipmentNumberLabel    = self.builder.get_object("eqEquipmentNumberLabel")
        self.eqEquipmentTypeLabel      = self.builder.get_object("eqEquipmentTypeLabel")
        self.eqMakeLabel               = self.builder.get_object("eqMakeLabel")
        self.eqEngineNumberLabel       = self.builder.get_object("eqEngineNumberLabel")
        self.eqPlateNumberLabel        = self.builder.get_object("eqPlateNumberLabel")
        self.eqChassisNumberLabel      = self.builder.get_object("eqChassisNumberLabel")
        self.eqRentalRateLabel         = self.builder.get_object("eqRentalRateLabel")
        self.eqUnitPriceLabel          = self.builder.get_object("eqUnitPriceLabel")
        self.eqLTOStatusLabel          = self.builder.get_object("eqLTOStatusLabel")
        self.eqAvailabilityStatusLabel = self.builder.get_object("eqAvailabilityStatusLabel")
        self.eqRegistrationDateLabel   = self.builder.get_object("eqRegistrationDateLabel")
        
        self.eqEquipmentNumberEntry       = self.builder.get_object("eqEquipmentNumberEntry")
        self.eqEquipmentTypeCombobox      = self.builder.get_object("eqEquipmentTypeCombobox")
        self.eqMakeEntry                  = self.builder.get_object("eqMakeEntry")
        self.eqEngineNumberEntry          = self.builder.get_object("eqEngineNumberEntry")
        self.eqPlateNumberEntry           = self.builder.get_object("eqPlateNumberEntry")
        self.eqChassisNumberEntry         = self.builder.get_object("eqChassisNumberEntry")
        self.eqRentalRateSpinButton       = self.builder.get_object("eqRentalRateSpinButton")
        self.eqUnitPriceCombobox          = self.builder.get_object("eqUnitPriceCombobox")
        self.eqLTOStatusCombobox          = self.builder.get_object("eqLTOStatusCombobox")
        self.eqAvailabilityStatusCombobox = self.builder.get_object("eqAvailabilityStatusCombobox")
        self.eqTypeCombobox               = self.builder.get_object("eqTypeCombobox")
        
        self.eqTypeListstore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.eqTypeListstore.append([_("All Equipment Types")])
        for instance in session.query(EquipmentType).order_by(EquipmentType.name):
            self.eqTypeListstore.append([instance.name])
            
        self.eqTypeCombobox.pack_start(cellRenderer, True)
        self.eqTypeCombobox.add_attribute(cellRenderer, "text", 0)
        self.eqTypeCombobox.set_model(self.eqTypeListstore)
        self.eqTypeCombobox.set_active(0)
        
        self.eqRegistrationDate = CalendarEntry("")
        self.eqStatusTable.attach(self.eqRegistrationDate, 1, 2, 2, 3)
        self.eqRegistrationDate.show_all()
        
        self.eqRentalRateSpinButton.set_range(0, 10000000)
        self.eqRentalRateSpinButton.set_increments(1, 1)
        
        self.create_eqComboboxes()
        
        self.eqWidgets = \
        [
            [self.eqEquipmentNumberEntry, self.eqEquipmentNumberLabel, _("Equipment _Number:"), True, 0], 
            [self.eqEquipmentTypeCombobox, self.eqEquipmentTypeLabel, _("Equipment _Type:"), True, 0], 
            [self.eqMakeEntry, self.eqMakeLabel, _("_Make:"), True, 0], 
            [self.eqEngineNumberEntry, self.eqEngineNumberLabel, _("_Engine Number:"), True, 0], 
            [self.eqPlateNumberEntry, self.eqPlateNumberLabel, _("_Plate Number:"), True, 0], 
            [self.eqChassisNumberEntry, self.eqChassisNumberLabel, _("C_hassis Number:"), True, 0], 
            [self.eqRentalRateSpinButton, self.eqRentalRateLabel, _("_Rental Rate:"), True, 1], 
            [self.eqUnitPriceCombobox, self.eqUnitPriceLabel, _("_Unit Price:"), True, 1],  
            [self.eqLTOStatusCombobox, self.eqLTOStatusLabel, _("_LTO Status:"), True, 2],  
            [self.eqAvailabilityStatusCombobox, self.eqAvailabilityStatusLabel, _("A_vailability Status:"), True, 2], 
            [self.eqRegistrationDate.entry, self.eqRegistrationDateLabel, _("_Registration Date:"), True, 2], 
        ]
        
        if DEBUG:
            
            print _("   Creating eqAddEditDialog.... Done")
        
    def create_cuAddEditDialog(self):
        
        self.cuAddEditDialog      = self.builder.get_object("cuAddEditDialog")
        
        self.cuPrefixLabel        = self.builder.get_object("cuPrefixLabel")
        self.cuLastnameEntry      = self.builder.get_object("cuLastnameEntry")
        self.cuFirstnameEntry     = self.builder.get_object("cuFirstnameEntry")
        self.cuMiddlenameEntry    = self.builder.get_object("cuMiddlenameEntry")
        self.cuContactnumberEntry = self.builder.get_object("cuContactnumberEntry")
        self.cuZipcodeEntry       = self.builder.get_object("cuZipcodeEntry")
        self.cuStreetEntry        = self.builder.get_object("cuStreetEntry")
        self.cuGenderCombobox     = self.builder.get_object("cuGenderCombobox")
        self.cuCityCombobox       = self.builder.get_object("cuCityCombobox")
        self.cuStateCombobox      = self.builder.get_object("cuStateCombobox")
        self.cuCountryCombobox    = self.builder.get_object("cuCountryCombobox")
        
        self.cuLastnameLabel      = self.builder.get_object("cuLastnameLabel")
        self.cuFirstnameLabel     = self.builder.get_object("cuFirstnameLabel")
        self.cuMiddlenameLabel    = self.builder.get_object("cuMiddlenameLabel")
        self.cuContactnumberLabel = self.builder.get_object("cuContactnumberLabel")
        self.cuGenderLabel        = self.builder.get_object("cuGenderLabel")
        self.cuStreetLabel        = self.builder.get_object("cuStreetLabel")
        self.cuCityLabel          = self.builder.get_object("cuCityLabel")
        self.cuZipcodeLabel       = self.builder.get_object("cuZipcodeLabel")
        self.cuStateLabel         = self.builder.get_object("cuStateLabel")
        self.cuCountryLabel       = self.builder.get_object("cuCountryLabel")
        
        self.cuContactnumberHbox  = self.builder.get_object("cuContactnumberHbox")
        
        #self.cuAddEditDialog.set_icon_from_file(os.path.join("img", "customer-new.png"))
        
        # create and pupulate some controls
        self.create_cuComboboxes()
        #self.populate_cuListstore()
        
        self.cuWidgets = \
        [
            [self.cuLastnameEntry, self.cuLastnameLabel, _("_Last Name:"), True], 
            [self.cuFirstnameEntry, self.cuFirstnameLabel, _("_First Name:"), True], 
            [self.cuMiddlenameEntry, self.cuMiddlenameLabel, _("_Middle Name:"), True], 
            [self.cuGenderCombobox, self.cuGenderLabel, _("_Gender:"), True], 
            [self.cuContactnumberEntry, self.cuContactnumberLabel, _("C_ontact Number:"), True], 
            [self.cuStreetEntry, self.cuStreetLabel, _("St_reet:"), True], 
            [self.cuZipcodeEntry, self.cuZipcodeLabel, _("_Zip Code:"), True], 
            [self.cuCountryCombobox, self.cuCountryLabel, _("Co_untry:"), True], 
            [self.cuStateCombobox, self.cuStateLabel, _("S_tate/Province:"), False], 
            [self.cuCityCombobox, self.cuCityLabel, _("C_ity/Town:"), False], 
        ]
        
        size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
        for widget in self.cuWidgets:
            
            if widget[2] != _("C_ontact Number:"):
                
                size_group.add_widget(widget[0])
                
            else:
                
                size_group.add_widget(self.cuContactnumberHbox)
                
        self.cuPrefixLabel.set_label(PREFIX)
        
        self.cuLastnameEntry.set_activates_default(True)
        self.cuFirstnameEntry.set_activates_default(True)
        self.cuMiddlenameEntry.set_activates_default(True)
        self.cuContactnumberEntry.set_activates_default(True)
        self.cuStreetEntry.set_activates_default(True)
        self.cuZipcodeEntry.set_activates_default(True)
        self.cuStateCombobox.set_sensitive(False)
        self.cuCityCombobox.set_sensitive(False)
        
        if DEBUG:
            
            print _("   Creating cuAddEditDialog.... Done")
            
    def create_maUserManagementDialog(self):
        
        self.create_maUsUserListstore()
        self.create_maWarehousesListstore()
        self.create_maOperatorsListstore()
        self.create_maUnitsListstore()
        self.maUsUserCountLabel = self.builder.get_object("maUsUserCountLabel")
        self.maUsOperatorCountLabel = self.builder.get_object("maUsOperatorCountLabel")
        self.maInWarehouseCountLabel = self.builder.get_object("maInWarehouseCountLabel")
        self.maInCategoryCountLabel = self.builder.get_object("maInCategoryCountLabel")
        self.maInUnitCountLabel = self.builder.get_object("maInUnitCountLabel")
        
        total_users = session.query(User).count()
        total_operators = session.query(Operator).count()
        total_warehouses = session.query(Warehouse).count()
        total_categories = session.query(Category).count()
        total_units = session.query(Unit).count()
        
        self.maUsUserCountLabel.set_text(_("%s Users" % (total_users)))
        self.maUsOperatorCountLabel.set_text(_("%s Operators" % (total_operators)))
        self.maInWarehouseCountLabel.set_text(_("%s Warehouses" % (total_warehouses)))
        self.maInCategoryCountLabel.set_text(_("%s Categories" % (total_categories)))
        self.maInUnitCountLabel.set_text(_("%s Units" % (total_units)))
        
        self.maUserManagementDialog = self.builder.get_object("maUserManagementDialog")
        self.maOperatorManagementDialog = self.builder.get_object("maOperatorManagementDialog")
        self.maWarehouseManagementDialog = self.builder.get_object("maWarehouseManagementDialog")
        self.maUnitManagementDialog = self.builder.get_object("maUnitManagementDialog")
        
        if DEBUG:
            
            print _("   Creating maUserManagementDialog.... Done")
            
    def create_warehouseAddEditDialog(self):
        
        self.warehouseAddEditDialog = self.builder.get_object("warehouseAddEditDialog")
        
        self.warehouseNameLabel = self.builder.get_object("warehouseNameLabel")
        self.warehouseNameEntry = self.builder.get_object("warehouseNameEntry")
        self.warehouseDescriptionLabel = self.builder.get_object("warehouseDescriptionLabel")
        self.warehouseDescriptionEntry = self.builder.get_object("warehouseDescriptionEntry")
        
        self.waWidgets = \
        [
            [self.warehouseNameEntry, self.warehouseNameLabel, _("_Name:"), True], 
            [self.warehouseDescriptionEntry, self.warehouseDescriptionLabel, _("_Description:"), True], 
        ]
        
    def create_operatorAddEditDialog(self):
        
        self.operatorAddEditDialog = self.builder.get_object("operatorAddEditDialog")
        
        self.operatorFirstNameLabel = self.builder.get_object("operatorFirstNameLabel")
        self.operatorFirstNameEntry = self.builder.get_object("operatorFirstNameEntry")
        self.operatorLastNameLabel = self.builder.get_object("operatorLastNameLabel")
        self.operatorLastNameEntry = self.builder.get_object("operatorLastNameEntry")
        
        self.opWidgets = \
        [
            [self.operatorFirstNameEntry, self.operatorFirstNameLabel, _("_First Name:"), True], 
            [self.operatorLastNameEntry, self.operatorLastNameLabel, _("_Last Name:"), True], 
        ]
        
    def create_unitAddEditDialog(self):
        
        self.unitAddEditDialog = self.builder.get_object("unitAddEditDialog")
        
        self.unitNameLabel = self.builder.get_object("unitNameLabel")
        self.unitNameEntry = self.builder.get_object("unitNameEntry")
        
        self.unWidgets = \
        [
            [self.unitNameEntry, self.unitNameLabel, _("_Name:"), True], 
        ]
        
    def create_userAddEditDialog(self):
        
        self.userAddEditDialog = self.builder.get_object("userAddEditDialog")
        
        self.userUsernameLabel = self.builder.get_object("userUsernameLabel")
        self.userPasswordLabel = self.builder.get_object("userPasswordLabel")
        self.userConfirmPasswordLabel = self.builder.get_object("userConfirmPasswordLabel")
        
        self.userUsernameEntry = self.builder.get_object("userUsernameEntry")
        self.userPasswordEntry = self.builder.get_object("userPasswordEntry")
        self.userConfirmPasswordEntry = self.builder.get_object("userConfirmPasswordEntry")
        
        self.userWarehouseTreeview = self.builder.get_object("userWarehouseTreeview")
        self.userCategoryTreeview = self.builder.get_object("userCategoryTreeview")

        
        self.userPassCheckLabel = self.builder.get_object("userPassCheckLabel")
        
        self.userWarehouseEntry = self.builder.get_object("userWarehouseEntry")
        self.userWarehouseAddButton = self.builder.get_object("userWarehouseAddButton")
        self.userWarehouseRemoveButton = self.builder.get_object("userWarehouseRemoveButton")
        
        self.userCategoryEntry = self.builder.get_object("userCategoryEntry")
        self.userCategoryAddButton = self.builder.get_object("userCategoryAddButton")
        self.userCategoryRemoveButton = self.builder.get_object("userCategoryRemoveButton")
        
        self.userWarehouseCompletion = gtk.EntryCompletion()
        self.userCategoryCompletion = gtk.EntryCompletion()
        
        self.userWarehouseListstore = gtk.ListStore(str)
        self.userCategoryListstore = gtk.ListStore(str)
        
        self.populate_userWarehouseListstore()
        self.populate_userCategoryListstore()
        
        self.userCategoryCompletion.set_model(self.userCategoryListstore)
        
        self.userCategoryEntry.set_completion(self.userCategoryCompletion)
        self.userCategoryCompletion.set_text_column(0)
        
        self.userWarehouseCompletion.set_model(self.userWarehouseListstore)

        self.userWarehouseEntry.set_completion(self.userWarehouseCompletion)
        self.userWarehouseCompletion.set_text_column(0)
        
        self.create_userWarehouseAddEditListstore()
        self.create_userCategoryAddEditListstore()
        
        self.permUsViewCheckbutton = self.builder.get_object("permUsViewCheckbutton")
        self.permInViewCheckbutton = self.builder.get_object("permInViewCheckbutton")
        self.permEqViewCheckbutton = self.builder.get_object("permEqViewCheckbutton")
        
        self.permUsAddCheckbutton = self.builder.get_object("permUsAddCheckbutton")
        self.permInAddCheckbutton = self.builder.get_object("permInAddCheckbutton")
        self.permEqAddCheckbutton = self.builder.get_object("permEqAddCheckbutton")
        
        self.permUsEditCheckbutton = self.builder.get_object("permUsEditCheckbutton")
        self.permInEditCheckbutton = self.builder.get_object("permInEditCheckbutton")
        self.permEqEditCheckbutton = self.builder.get_object("permEqEditCheckbutton")
        
        self.permUsDeleteCheckbutton = self.builder.get_object("permUsDeleteCheckbutton")
        self.permInDeleteCheckbutton = self.builder.get_object("permInDeleteCheckbutton")
        self.permEqDeleteCheckbutton = self.builder.get_object("permEqDeleteCheckbutton")
        
        self.permExViewCheckbutton = self.builder.get_object("permExViewCheckbutton")
        self.permExAddCheckbutton = self.builder.get_object("permExAddCheckbutton")
        
        self.permReViewCheckbutton = self.builder.get_object("permReViewCheckbutton")
        self.permMaViewCheckbutton = self.builder.get_object("permMaViewCheckbutton")
        
        self.di = \
        {
            'view_user':self.permUsViewCheckbutton, 'add_user':self.permUsAddCheckbutton, 
            'edit_user':self.permUsEditCheckbutton, 'delete_user':self.permUsDeleteCheckbutton, 
            'view_inventory':self.permInViewCheckbutton, 'add_inventory':self.permInAddCheckbutton, 
            'edit_inventory':self.permInEditCheckbutton, 'delete_inventory':self.permInDeleteCheckbutton, 
            'view_equipment':self.permEqViewCheckbutton, 'add_equipment':self.permEqAddCheckbutton, 
            'edit_equipment':self.permEqEditCheckbutton, 'delete_equipment':self.permEqDeleteCheckbutton, 
            'view_expense':self.permExViewCheckbutton, 'add_expense':self.permExAddCheckbutton, 
            'view_report':self.permReViewCheckbutton, 'view_maintenance':self.permMaViewCheckbutton, 
        }
        
        self.usWidgets = \
        [
            [self.userUsernameEntry, self.userUsernameLabel, _("_Username:"), True], 
            [self.userPasswordEntry, self.userPasswordLabel, _("_Password:"), True], 
            [self.userConfirmPasswordEntry, self.userConfirmPasswordLabel, _("C_onfirm Password:"), True], 
        ]
        
        if DEBUG:
            
            print _("   Creating userAddEditDialog.... Done")
        
    def create_expenseAddEditDialog(self):
        
        self.create_exListstore()
        self.create_exItListstore()
        self.exItList = []
        self.expenseAddEditDialog = self.builder.get_object("expenseAddEditDialog")
        
        self.exExExFrame = self.builder.get_object("exExExFrame")
        self.exExItFrame = self.builder.get_object("exExItFrame")
        self.exExReFrame = self.builder.get_object("exExReFrame")
        self.exExSaFrame = self.builder.get_object("exExSaFrame")
        
        self.exEqUnitLabel = self.builder.get_object("exEqUnitLabel")
        self.exEqPlateLabel = self.builder.get_object("exEqPlateLabel")
        
        self.exEqUnitCombobox = self.builder.get_object("exEqUnitCombobox")
        self.exEqPlateLabelValue = self.builder.get_object("exEqPlateLabelValue")
        
        self.exUnitLabel = self.builder.get_object("exUnitLabel")
        self.exAddPurchaseButton = self.builder.get_object("exAddPurchaseButton")
        self.exQuantitySpinbutton = self.builder.get_object("exQuantitySpinbutton")
        self.exTotalLabelValue = self.builder.get_object("exTotalLabelValue")
        self.exExPONumberLabel = self.builder.get_object("exExPONumberLabel")
        self.exExDateLabel = self.builder.get_object("exExDateLabel")
        
        self.exExReDateLabel = self.builder.get_object("exExReDateLabel")
        self.exExReScopeEntry = self.builder.get_object("exExReScopeEntry")
        self.exExReScopeLabel = self.builder.get_object("exExReScopeLabel")
        self.exExReLaborSpinbutton = self.builder.get_object("exExReLaborSpinbutton")
        self.exExReLaborLabel = self.builder.get_object("exExReLaborLabel")
        self.exExReServiceEntry = self.builder.get_object("exExReServiceEntry")
        self.exExReServiceLabel = self.builder.get_object("exExReServiceLabel")
        
        self.exExSaDateLabel = self.builder.get_object("exExSaDateLabel")
        self.exExSaOperatorLabel = self.builder.get_object("exExSaOperatorLabel")
        self.exExSaOperatorCombobox = self.builder.get_object("exExSaOperatorCombobox")
        self.exExSaAmountSpinbutton = self.builder.get_object("exExSaAmountSpinbutton")
        self.exExSaAmountLabel = self.builder.get_object("exExSaAmountLabel")
        self.exExSaRemarksLabel = self.builder.get_object("exExSaRemarksLabel")
        self.exExSaRemarksEntry = self.builder.get_object("exExSaRemarksEntry")
        
        self.exExPONumberEntry = self.builder.get_object("exExPONumberEntry")
        
        self.exExTable = self.builder.get_object("exExTable")
        self.exExReTable = self.builder.get_object("exExReTable")
        self.exExSaTable = self.builder.get_object("exExSaTable")
        
        self.exItemCombobox = self.builder.get_object("exItemCombobox")
        
        self.exExDate = CalendarEntry("")
        self.exExTable.attach(self.exExDate, 1, 2, 1, 2)
        self.exExDate.show_all()
        
        self.exExReDate = CalendarEntry("")
        self.exExReTable.attach(self.exExReDate, 1, 2, 0, 1)
        self.exExReDate.show_all()
        
        self.exExSaDate = CalendarEntry("")
        self.exExSaTable.attach(self.exExSaDate, 1, 2, 0, 1)
        self.exExSaDate.show_all()
        
        self.exUnitListStore = gtk.ListStore(str)
        self.exOperatorListStore = gtk.ListStore(str)
        self.exItemListStore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.exEqUnitCombobox.pack_start(cellRenderer, True)
        self.exEqUnitCombobox.add_attribute(cellRenderer, "text", 0)
        self.exItemCombobox.pack_start(cellRenderer, True)
        self.exItemCombobox.add_attribute(cellRenderer, "text", 0)
        self.exExSaOperatorCombobox.pack_start(cellRenderer, True)
        self.exExSaOperatorCombobox.add_attribute(cellRenderer, "text", 0)
        
        # Units
        self.populate_exUnitListStore()
        
        # Items
        self.populate_exItemListStore()
        
        self.populate_exOperatorListStore()
        
        self.exWidgets = \
        [
            [self.exEqUnitCombobox, self.exEqUnitLabel, _("_Unit:"), True, 0], 
            [self.exExPONumberEntry, self.exExPONumberLabel, _("_P.O. Number:"), True, 0], 
            [self.exExDate.entry, self.exExDateLabel, _("_Date:"), True, 0], 
        ]
        
        self.exReWidgets = \
        [
            [self.exEqUnitCombobox, self.exEqUnitLabel, _("_Unit:"), True, 0], 
            [self.exExReDate.entry, self.exExReDateLabel, _("_Date:"), True, 0], 
            [self.exExReScopeEntry, self.exExReScopeLabel, _("Sc_ope of Works:"), True, 0], 
            [self.exExReLaborSpinbutton, self.exExReLaborLabel, _("_Labor Charge:"), True, 0], 
            [self.exExReServiceEntry, self.exExReServiceLabel, _("Se_rvice Provider:"), True, 0], 
        ]
        
        self.exSaWidgets = \
        [
            [self.exEqUnitCombobox, self.exEqUnitLabel, _("_Unit:"), True, 0], 
            [self.exExSaDate.entry, self.exExSaDateLabel, _("_Date:"), True, 0], 
            [self.exExSaOperatorCombobox, self.exExSaOperatorLabel, _("O_perator:"), True, 0], 
            [self.exExSaAmountSpinbutton, self.exExSaAmountLabel, _("_Amount:"), True, 0], 
            [self.exExSaRemarksEntry, self.exExSaRemarksLabel, _("_Remarks:"), True, 0], 
        ]
        
        self.exExReLaborSpinbutton.set_range(0, 99999999)
        self.exExReLaborSpinbutton.set_increments(1, 1)
        self.exExReLaborSpinbutton.set_sensitive(True)
        
        self.exExSaAmountSpinbutton.set_range(0, 99999999)
        self.exExSaAmountSpinbutton.set_increments(1, 1)
        self.exExSaAmountSpinbutton.set_sensitive(True)
        
        for expense in session.query(Expense).order_by(Expense.id):
            
            self.update_exListstore(expense)
        
    def create_reportDetailsDialog(self):
        
        self.create_rePartsListstore()
        self.create_reFuelListstore()
        self.create_reRepairListstore()
        self.create_reSalaryListstore()
        
        self.reportDetailsDialog = self.builder.get_object("reportDetailsDialog")
        self.reportNotebook = self.builder.get_object("reportNotebook")
        
        self.reUnitLabelValue = self.builder.get_object("reUnitLabelValue")
        self.rePlateLabelValue = self.builder.get_object("rePlateLabelValue")
        self.reUnitSpecsLabelValue = self.builder.get_object("reUnitSpecsLabelValue")
        
        self.reFromTable = self.builder.get_object("reFromTable")
        self.reToTable = self.builder.get_object("reToTable")
        
        self.reRepairTotalLabel = self.builder.get_object("reRepairTotalLabel")
        self.reSalaryTotalLabel = self.builder.get_object("reSalaryTotalLabel")
        
        self.reportEntry = self.builder.get_object("reportEntry")
        self.reportTypeCombobox = self.builder.get_object("reportTypeCombobox")
        
        self.reportFindButton = self.builder.get_object("reportFindButton")
        
        self.reportEquipmentTypeListStore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.reportTypeCombobox.pack_start(cellRenderer, True)
        self.reportTypeCombobox.add_attribute(cellRenderer, "text", 0)
        
        # Equipment Types
        self.reportEquipmentTypeListStore.append([_("All Equipment Types")])
        for equipment_type in session.query(EquipmentType).order_by(EquipmentType.name):
            
            self.reportEquipmentTypeListStore.append([equipment_type.name])
            
        self.reportTypeCombobox.set_model(self.reportEquipmentTypeListStore)
        self.reportTypeCombobox.set_active(0)
        
        self.rePartsTotalLabel = self.builder.get_object("rePartsTotalLabel")
        self.reFuelTotalLabel = self.builder.get_object("reFuelTotalLabel")
        
        self.reSummaryPartsLabel = self.builder.get_object("reSummaryPartsLabel")
        self.reSummaryFuelLabel = self.builder.get_object("reSummaryFuelLabel")
        self.reSummaryRepairLabel = self.builder.get_object("reSummaryRepairLabel")
        self.reSummarySalaryLabel = self.builder.get_object("reSummarySalaryLabel")
        
        
        self.reFromDate = CalendarEntry("")
        self.reFromTable.attach(self.reFromDate, 1, 2, 0, 1)
        self.reFromDate.show_all()
        
        self.reToDate = CalendarEntry("")
        self.reToTable.attach(self.reToDate, 1, 2, 0, 1)
        self.reToDate.show_all()
        
    def create_eqComboboxes(self):
        
        self.eqEquipmentTypeListStore = gtk.ListStore(str)
        self.eqUnitPriceListStore = gtk.ListStore(str)
        self.eqLTOStatusListStore = gtk.ListStore(str)
        self.eqAvailabilityStatusListStore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.eqEquipmentTypeCombobox.pack_start(cellRenderer, True)
        self.eqEquipmentTypeCombobox.add_attribute(cellRenderer, "text", 0)
        self.eqUnitPriceCombobox.pack_start(cellRenderer, True)
        self.eqUnitPriceCombobox.add_attribute(cellRenderer, "text", 0)
        self.eqLTOStatusCombobox.pack_start(cellRenderer, True)
        self.eqLTOStatusCombobox.add_attribute(cellRenderer, "text", 0)
        self.eqAvailabilityStatusCombobox.pack_start(cellRenderer, True)
        self.eqAvailabilityStatusCombobox.add_attribute(cellRenderer, "text", 0)
        
        # Equipment Types
        self.eqEquipmentTypeListStore.append([_("Select one")])
        for equipment_type in session.query(EquipmentType).order_by(EquipmentType.name):
            
            self.eqEquipmentTypeListStore.append([equipment_type.name])
            
        self.eqEquipmentTypeCombobox.set_model(self.eqEquipmentTypeListStore)
        self.eqEquipmentTypeCombobox.set_active(0)
        
        # Equipment Unit Price
        self.eqUnitPriceListStore.append([_("Select one")])
        for equipment_unit in session.query(EquipmentUnit).order_by(EquipmentUnit.name):
            
            self.eqUnitPriceListStore.append([equipment_unit.name])
            
        self.eqUnitPriceCombobox.set_model(self.eqUnitPriceListStore)
        self.eqUnitPriceCombobox.set_active(0)
        
        # Equipment LTO Status
        self.eqLTOStatusListStore.append([_("Select one")])
        for lto_status in session.query(LTOStatus).order_by(LTOStatus.name):
            
            self.eqLTOStatusListStore.append([lto_status.name])
            
        self.eqLTOStatusCombobox.set_model(self.eqLTOStatusListStore)
        self.eqLTOStatusCombobox.set_active(0)
        
        # Equipment Availability Status
        self.eqAvailabilityStatusListStore.append([_("Select one")])
        for equipment_status in session.query(EquipmentStatus).order_by(EquipmentStatus.name):
            
            self.eqAvailabilityStatusListStore.append([equipment_status.name])
            
        self.eqAvailabilityStatusCombobox.set_model(self.eqAvailabilityStatusListStore)
        self.eqAvailabilityStatusCombobox.set_active(0)
        
    def create_cuComboboxes(self):
        
        self.cuGenderListStore = gtk.ListStore(str)
        self.cuCityListStore = gtk.ListStore(str)
        self.cuStateListStore = gtk.ListStore(str)
        self.cuCountryListStore = gtk.ListStore(str)
        cellRenderer = gtk.CellRendererText()
        
        self.cuGenderCombobox.pack_start(cellRenderer, True)
        self.cuGenderCombobox.add_attribute(cellRenderer, "text", 0)
        self.cuCityCombobox.pack_start(cellRenderer, True)
        self.cuCityCombobox.add_attribute(cellRenderer, "text", 0)
        self.cuStateCombobox.pack_start(cellRenderer, True)
        self.cuStateCombobox.add_attribute(cellRenderer, "text", 0)
        self.cuCountryCombobox.pack_start(cellRenderer, True)
        self.cuCountryCombobox.add_attribute(cellRenderer, "text", 0)
        
        # Gender
        li = [_("Select one"), _("Male"), _("Female")]
        for item in li:
            
            self.cuGenderListStore.append([item])
            
        # City
        self.cuCityListStore.append([_("Select one")])
        #for city in session.query(City):
            
        #    self.cuCityListStore.append([city.name])
            
        # State
        self.cuStateListStore.append([_("Select one")])
        for state in session.query(StateCity).order_by(StateCity.name):
            
            self.cuStateListStore.append([state.name])
            
        # Country
        self.cuCountryListStore.append([_("Select one")])
        for country in session.query(Country).order_by(Country.name):
            
            self.cuCountryListStore.append([country.name])
            
        self.cuGenderCombobox.set_model(self.cuGenderListStore)
        self.cuGenderCombobox.set_active(0)
        self.cuCityCombobox.set_model(self.cuCityListStore)
        self.cuCityCombobox.set_active(0)
        self.cuStateCombobox.set_model(self.cuStateListStore)
        self.cuStateCombobox.set_active(0)
        self.cuCountryCombobox.set_model(self.cuCountryListStore)
        self.cuCountryCombobox.set_active(0)
        
    #***************************************************************************
    # Signal Handlers
    #***************************************************************************
    def on_mainWindow_destroy(self, widget):
        """Called when the application is going to quit"""
        
        gtk.main_quit()
        
    def on_preferenceDialog_activate(self, widget):
        
        print widget
        
    def on_aboutDialog_close(self, widget, event):
        
        self.aboutDialog.hide()
        
    def on_userWarehouseAddButton_clicked(self, widget, entry_value=None, s=None):
        
        if entry_value is None:
            
            entry_value = self.userWarehouseEntry.get_text()
            
        if s is None:
            
            s = session
            
        warehouse = []
        in_liststore = False
        
        try:
            
            w = s.query(Warehouse).filter(entry_value==Warehouse.name).one()
            
            warehouse.extend([w, w.id, w.name])
            
        except NoResultFound:
            
            return
        
        _iter = self.userWarehouseAddEditListstore.get_iter_first()
        
        while _iter is not None:
            
            value = self.userWarehouseAddEditListstore.get_value(_iter, 2)
            
            if value == w.name:
                
                in_liststore = True
                
            _iter = self.userWarehouseAddEditListstore.iter_next(_iter)
            
        if not in_liststore:
            
            self.userWarehouseAddEditListstore.append(warehouse)
            
        self.userWarehouseEntry.set_text("")
        self.userWarehouseEntry.grab_focus()
        
        
    def on_userWarehouseRemoveButton_clicked(self, widget):
        
        selected_row = self.userWarehouseTreeview.get_selection().get_selected_rows()
        
        _iter = self.userWarehouseAddEditListstore.get_iter(selected_row[1][0])
        self.userWarehouseAddEditListstore.remove(_iter)
        
        self.userWarehouseTreeview.get_selection().unselect_all()
        self.userWarehouseRemoveButton.set_sensitive(False)
        
    def on_userCategoryAddButton_clicked(self, widget, entry_value=None, s=None):
        
        if entry_value is None:
            
            entry_value = self.userCategoryEntry.get_text()
            
        if s is None:
            
            s = session
            
        category = []
        in_liststore = False
        
        try:
            
            c = s.query(Category).filter(entry_value==Category.name).one()
            
            category.extend([c, c.id, c.name])
            
        except NoResultFound:
            
            return
        
        _iter = self.userCategoryAddEditListstore.get_iter_first()
        
        while _iter is not None:
            
            value = self.userCategoryAddEditListstore.get_value(_iter, 2)
            
            if value == c.name:
                
                in_liststore = True
                
            _iter = self.userCategoryAddEditListstore.iter_next(_iter)
            
        if not in_liststore:
            
            self.userCategoryAddEditListstore.append(category)
            
        self.userCategoryEntry.set_text("")
        self.userCategoryEntry.grab_focus()
        
        
    def on_userCategoryRemoveButton_clicked(self, widget):
        
        selected_row = self.userCategoryTreeview.get_selection().get_selected_rows()
        
        _iter = self.userCategoryAddEditListstore.get_iter(selected_row[1][0])
        self.userCategoryAddEditListstore.remove(_iter)
        
        self.userCategoryTreeview.get_selection().unselect_all()
        self.userCategoryRemoveButton.set_sensitive(False)
        
    def on_aboutDialog_activate(self, widget):
        
        self.aboutDialog.run()
        
    def on_inEntries_focus_in_event(self, widget, event):
        
        self.inGenresRemoveButton.set_sensitive(False)
        self.inCastsRemoveButton.set_sensitive(False)
        self.inWritersRemoveButton.set_sensitive(False)
        
        self.inGenresTreeview.get_selection().unselect_all()
        self.inCastsTreeview.get_selection().unselect_all()
        self.inWritersTreeview.get_selection().unselect_all()
        
    def on_maUsAddUserButton_clicked(self, widget):
        
        self.reset_widgets(self.usWidgets)
        
        for k in self.di.keys():
                
                self.di[k].set_active(False)
        
        self.userWarehouseAddEditListstore.clear()
        self.userCategoryAddEditListstore.clear()
        result = self.userAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and (
              self.validate_widgets(self.usWidgets) == -1 or \
              self.userPasswordEntry.get_text() != self.userConfirmPasswordEntry.get_text()):
        
            result = self.userAddEditDialog.run()
            self.reset_widgets(self.usWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            user = self.userUsernameEntry.get_text()
            pwd  = self.userPasswordEntry.get_text()
            cpwd = self.userConfirmPasswordEntry.get_text()
            
            permission_dict = {}
            
            for k in self.di.keys():
                
                permission_dict[k] = self.di[k].get_active()
                
            self.userWarehouseSelectedList = []
            self.userCategorySelectedList = []
            
            _iter = self.userWarehouseAddEditListstore.get_iter_first()
            while _iter is not None:
            
                self.userWarehouseSelectedList.append(self.userWarehouseAddEditListstore.get_value(_iter, 0).id)
            
                _iter = self.userWarehouseAddEditListstore.iter_next(_iter)
        
            _iter = self.userCategoryAddEditListstore.get_iter_first()
            while _iter is not None:
            
                self.userCategorySelectedList.append(self.userCategoryAddEditListstore.get_value(_iter, 0).id)
            
                _iter = self.userCategoryAddEditListstore.iter_next(_iter)
                
            permission_dict['warehouse_access'] = self.userWarehouseSelectedList
            permission_dict['category_access']  = self.userCategorySelectedList
                
            u = User(user, pwd)
            u.user_type = 2
            u.set_permissions(permission_dict)
            
            session.add(u)
            session.commit()
            
            item = []
            item.append(u)
            item.append(u.id)
            item.append(u.type)
            item.append(u.username)
                
            self.maUsUserListstore.append(item)
        
        self.reset_widgets(self.usWidgets)
        self.userAddEditDialog.hide()
        
    def on_addStockButton_clicked(self, widget):
        
        result = self.stockAddDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.stockWidgets) == -1:
            
            result = self.stockAddDialog.run()
            self.reset_widgets(self.stockWidgets, False)
            
        self.stockAddDialog.hide()
        
        if result == gtk.RESPONSE_OK:
            
            credit = self.stockStockSpinButton.get_value_as_int()
            unit_price = "%.2f" % self.stockUnitPriceSpinButton.get_value()
            description = self.stockDescriptionEntry.get_text()
            
            warehouse_name = self.get_combobox_value(self.stockWarehouseCombobox)
            warehouse = session.query(Warehouse).filter_by(name=warehouse_name).one()
            
            stock = Stock(datetime.datetime.now(), credit, 0, unit_price, description, warehouse.id)
            stock.warehouse = warehouse
            
            #session.add(stock)
            
            self.update_inStockListstore([stock])
            
        self.reset_widgets(self.stockWidgets)
        
    def on_inIMDBConnectButton_clicked(self, widget):
        
        thread = IMDBConnectThread()
        thread.start()
        
    def on_maUnitsTreeview_row_activated(self, treeview, path, column):
        
        self.unitAddEditDialog.set_title(_("Edit Unit Dialog"))
        
        uModel = treeview.get_model()
        uIter  = uModel.get_iter(path)
        
        u = uModel.get_value(uIter, 0)
        
        self.unitNameEntry.set_text(u.name)
        
        result = self.unitAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.unWidgets) == -1:
            
            result = self.unitAddEditDialog.run()
            
            self.reset_widgets(self.unWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            u.name = self.unitNameEntry.get_text()
            
            session.commit()
            
            self.maUnitsListstore.set(uIter, 
                0, u, 
                1, u.id,
                2, u.name)
            
            self.populate_itemUnitListstore()
        
        else:
            
            session.rollback()
            
        self.reset_widgets(self.unWidgets)
        self.unitAddEditDialog.hide()
        
    def on_maWarehousesTreeview_row_activated(self, treeview, path, column):
        
        self.warehouseAddEditDialog.set_title(_("Edit Warehouse Dialog"))
        
        wModel = treeview.get_model()
        wIter  = wModel.get_iter(path)
        
        w = wModel.get_value(wIter, 0)
        
        self.warehouseNameEntry.set_text(w.name)
        self.warehouseDescriptionEntry.set_text(w.description)
        
        result = self.warehouseAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.waWidgets) == -1:
            
            result = self.warehouseAddEditDialog.run()
            
            self.reset_widgets(self.waWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            w.name = self.warehouseNameEntry.get_text()
            w.description = self.warehouseDescriptionEntry.get_text()
            
            session.commit()
            
            self.maWarehousesListstore.set(wIter, 
                0, w, 
                1, w.id,
                2, w.name,
                3, w.description)
            
            self.populate_userWarehouseListstore()
        
        else:
            
            session.rollback()
            
        self.reset_widgets(self.waWidgets)
        self.warehouseAddEditDialog.hide()
        
    def on_maOperatorsTreeview_row_activated(self, treeview, path, column):
        
        self.operatorAddEditDialog.set_title(_("Edit Operator Dialog"))
        
        oModel = treeview.get_model()
        oIter  = oModel.get_iter(path)
        
        o = oModel.get_value(oIter, 0)
        
        self.operatorFirstNameEntry.set_text(o.first_name)
        self.operatorLastNameEntry.set_text(o.last_name)
        
        result = self.operatorAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.opWidgets) == -1:
            
            result = self.operatorAddEditDialog.run()
            
            self.reset_widgets(self.waWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            o.first_name = self.operatorFirstNameEntry.get_text()
            o.last_name = self.operatorLastNameEntry.get_text()
            
            session.commit()
            
            self.maOperatorsListstore.set(oIter, 
                0, o, 
                1, o.id,
                2, o.last_name,
                3, o.first_name)
        
        else:
            
            session.rollback()
            
        self.reset_widgets(self.opWidgets)
        self.operatorAddEditDialog.hide()
        
    def on_maUnitAddUserButton_clicked(self, widget):
        
        result = self.unitAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.unWidgets) == -1:
            
            result = self.unitAddEditDialog.run()
            
            self.reset_widgets(self.unWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            name = self.unitNameEntry.get_text()
            
            u = Unit(name)
            
            session.add(u)
            session.commit()
            
            self.maUnitsListstore.append([u, u.id, u.name])
            
            self.populate_itemUnitListstore()
            
        self.reset_widgets(self.unWidgets)
        self.unitAddEditDialog.hide()
        
    def on_maWarehouseAddUserButton_clicked(self, widget):
        
        result = self.warehouseAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.waWidgets) == -1:
            
            result = self.warehouseAddEditDialog.run()
            
            self.reset_widgets(self.waWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            name = self.warehouseNameEntry.get_text()
            desc = self.warehouseDescriptionEntry.get_text()
            
            w = Warehouse(name, desc)
            
            session.add(w)
            session.commit()
            
            self.maWarehousesListstore.append([w, w.id, w.name, w.description])
            self.populate_userWarehouseListstore()
        
            
        self.reset_widgets(self.waWidgets, False)
        self.warehouseAddEditDialog.hide()
        
    def on_maOperatorAddUserButton_clicked(self, widget):
        
        result = self.operatorAddEditDialog.run()
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.opWidgets) == -1:
            
            result = self.operatorAddEditDialog.run()
            
            self.reset_widgets(self.opWidgets, False)
        
        if (result == gtk.RESPONSE_OK):
            
            f = self.operatorFirstNameEntry.get_text()
            l = self.operatorLastNameEntry.get_text()
            
            o = Operator(f, l)
            
            session.add(o)
            session.commit()
            
            self.maOperatorsListstore.append([o, o.id, o.first_name, o.last_name])
            #self.populate_userWarehouseListstore()
        
            
        self.reset_widgets(self.opWidgets, False)
        self.operatorAddEditDialog.hide()
        
    def on_userSaveButton_clicked(self, widget):
        
        pass
        
    def on_eqAddButton_clicked(self, widget):
        
        self.eqEquipmentNumberEntry.grab_focus()
        
        self.eqAddEditDialog.set_title(_("Add Equipment Dialog"))
        
        result = self.eqAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.eqWidgets, self.eqAddEditNotebook) == -1:
            
            result = self.eqAddEditDialog.run()
            
            self.reset_widgets(self.eqWidgets, False, self.eqAddEditNotebook)
            
        self.eqAddEditDialog.hide()
        
        if result == gtk.RESPONSE_OK:
            
            self.eqPerformAdd()
            
        self.reset_widgets(self.eqWidgets, notebook=self.eqAddEditNotebook)
        
    def on_inAddButton_clicked(self, widget):
        
        self.itemNameEntry.grab_focus()
        self.inStockListstore.clear()
        
        self.itemAddEditDialog.set_title(_("Add Item Dialog"))
        
        result = self.itemAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.itemWidgets) == -1:
            
            result = self.itemAddEditDialog.run()
            
            self.reset_widgets(self.itemWidgets, False)
            
        self.itemAddEditDialog.hide()
        
        if result == gtk.RESPONSE_OK:
            
            self.inPerformAdd()
            
        else:
            
            session.rollback()
            
        self.reset_widgets(self.itemWidgets)
        
    def on_inGenresTreeview_cursor_changed(self, widget):
        
        pass
        
    def on_userWarehouseTreeview_cursor_changed(self, widget):
        
        self.userWarehouseRemoveButton.set_sensitive(True)
        
    def on_userCategoryTreeview_cursor_changed(self, widget):
        
        self.userCategoryRemoveButton.set_sensitive(True)
        
    def on_inCastsTreeview_cursor_changed(self, widget):
        
        self.inCastsRemoveButton.set_sensitive(True)
        
    def on_inWritersTreeview_cursor_changed(self, widget):
        
        self.inWritersRemoveButton.set_sensitive(True)
        
    def on_inGenresAddButton_clicked(self, widget, entry_value=None, s=None):
        
        if entry_value is None:
            
            entry_value = self.inGenresEntry.get_text()
            
        if s is None:
            
            s = session
            
        genre = []
        in_liststore = False
        
        try:
            
            g = s.query(Genre).filter(entry_value==Genre.name).one()
            
            genre.extend([g, g.id, g.name])
            
        except NoResultFound:
            
            return
        
        _iter = self.inGenresAddEditListstore.get_iter_first()
        
        while _iter is not None:
            
            value = self.inGenresAddEditListstore.get_value(_iter, 2)
            
            if value == g.name:
                
                in_liststore = True
                
            _iter = self.inGenresAddEditListstore.iter_next(_iter)
            
        if not in_liststore:
            
            self.inGenresAddEditListstore.append(genre)
            
        self.inGenresEntry.set_text("")
        self.inGenresEntry.grab_focus()
        
    def on_inCastsAddButton_clicked(self, widget, entry_value=None, s=None):
        
        if entry_value is None:
            
            entry_value = convert_HTMLToUnicode(self.inCastsEntry.get_text())
            
        if s is None:
            
            s = session
            
        cast = []
        in_liststore = False
        
        try:
            
            c = s.query(Cast).\
              filter(convert_HTMLToUnicode(entry_value)==Cast.full_name).one()
            
            cast.extend([c, c.id, c.full_name])
            
        except NoResultFound:
            
            if entry_value != "":
                
                c = Cast(entry_value)
                
                cast.extend([c, -1, c.full_name])
                
                self.inCastsListstore.append([c.full_name])
                
            else:
                
                return
            
        _iter = self.inCastsAddEditListstore.get_iter_first()
        
        while _iter is not None:
            
            value = self.inCastsAddEditListstore.get_value(_iter, 2)
            
            if value == c.full_name:
                
                in_liststore = True
                
            _iter = self.inCastsAddEditListstore.iter_next(_iter)
            
        if not in_liststore:
            
            self.inCastsAddEditListstore.append(cast)
            
        self.inCastsEntry.set_text("")
        self.inCastsEntry.grab_focus()
        
    def on_inWritersAddButton_clicked(self, widget, entry_value=None, s=None):
        
        if entry_value is None:
            
            entry_value = convert_HTMLToUnicode(self.inWritersEntry.get_text())
            
        if s is None:
            
            s = session
            
        writer = []
        in_liststore = False
        
        try:
            
            w = s.query(Writer).\
              filter(convert_HTMLToUnicode(entry_value)==Writer.full_name).one()
            
            writer.extend([w, w.id, w.full_name])
            
        except NoResultFound:
            
            if entry_value != "":
                
                w = Writer(entry_value)
                
                writer.extend([w, -1, w.full_name])
                
                self.inWritersListstore.append([w.full_name])
                
            else:
                
                return
            
        _iter = self.inWritersAddEditListstore.get_iter_first()
        
        while _iter is not None:
            
            value = self.inWritersAddEditListstore.get_value(_iter, 2)
            
            if value == w.full_name:
                
                in_liststore = True
                
            _iter = self.inWritersAddEditListstore.iter_next(_iter)
            
        if not in_liststore:
            
            self.inWritersAddEditListstore.append(writer)
            
        self.inWritersEntry.set_text("")
        self.inWritersEntry.grab_focus()
        
    def on_inGenresRemoveButton_clicked(self, widget):
        
        selected_row = self.inGenresTreeview.get_selection().get_selected_rows()
        
        _iter = self.inGenresAddEditListstore.get_iter(selected_row[1][0])
        self.inGenresAddEditListstore.remove(_iter)
        
        self.inGenresTreeview.get_selection().unselect_all()
        self.inGenresRemoveButton.set_sensitive(False)
        
    def on_inCastsRemoveButton_clicked(self, widget):
        
        selected_row = self.inCastsTreeview.get_selection().get_selected_rows()
        
        _iter = self.inCastsAddEditListstore.get_iter(selected_row[1][0])
        self.inCastsAddEditListstore.remove(_iter)
        
        self.inCastsTreeview.get_selection().unselect_all()
        self.inCastsRemoveButton.set_sensitive(False)
        
    def on_inWritersRemoveButton_clicked(self, widget):
        
        selected_row = self.inWritersTreeview.get_selection().get_selected_rows()
        
        _iter = self.inWritersAddEditListstore.get_iter(selected_row[1][0])
        self.inWritersAddEditListstore.remove(_iter)
        
        self.inWritersTreeview.get_selection().unselect_all()
        self.inWritersRemoveButton.set_sensitive(False)
        
    def on_inImdbCodeEntry_changed(self, widget):
    
        text = widget.get_text()
        if len(text) != 9:
            
            self.inIMDBConnectButton.set_sensitive(False)
            return
        
        elif text[0:2] == "tt" and isinstance(eval(text[2:]), int):
        
            self.inIMDBConnectButton.set_sensitive(True)
            
        else:
            
            self.inIMDBConnectButton.set_sensitive(False)
            
    def on_inEntry_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() in ('Linux', 'Darwin')):
            
            self.on_inFindButton_clicked(widget)
            
    def on_inImdbCodeEntry_key_press_event(self, widget, event):
    
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() in ('Linux', 'Darwin')):
        
            self.on_inIMDBConnectButton_clicked(widget)
        
    def on_inGenresEntry_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            self.on_inGenresAddButton_clicked(widget)
            
    def on_inCastsEntry_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            self.on_inCastsAddButton_clicked(widget)
            
    def on_inWritersEntry_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            self.on_inWritersAddButton_clicked(widget)
            
    def on_reTreeview_row_activated(self, treeview, path, column):
        
        usModel = treeview.get_model()
        usIter  = usModel.get_iter(path)
        
        it = usModel.get_value(usIter, 0)
        self.equipment = it
        
        self.reUnitLabelValue.set_markup_with_mnemonic(_("Unit: <b>%s</b>" % it.number))
        self.rePlateLabelValue.set_markup_with_mnemonic(_("Plate No: <b>%s</b>" % it.plate_number))
        self.reUnitSpecsLabelValue.set_markup_with_mnemonic(_("Unit Specs:"))
        
        d = datetime.datetime.now()
        days_in_a_month = calendar.mdays[datetime.date.today().month]
        
        fr = datetime.datetime(d.year, d.month, 1)
        to = datetime.datetime(d.year, d.month, days_in_a_month)
        
        self.reFromDate.set_date(fr)
        self.reToDate.set_date(to)
        
        self.on_reQueryButton_clicked(self)
        
        self.reportDetailsDialog.run()
        self.reportDetailsDialog.hide()
        
        self.reportNotebook.set_current_page(0)
        
    def on_maUsersTreeview_row_activated(self, treeview, path, column):
        
        if not self.current_permissions["edit_user"]:
            
            return
        
        self.userAddEditDialog.set_title(_("Edit User Dialog"))
        
        usModel = treeview.get_model()
        usIter  = usModel.get_iter(path)
        
        it = usModel.get_value(usIter, 0)
        permissions = it.get_permissions()
        
        self.password = it.password
        
        self.userUsernameEntry.set_text(it.username)
        self.userPasswordEntry.set_text(it.password)
        self.userConfirmPasswordEntry.set_text(it.password)
        
        self.userWarehouseAddEditListstore.clear()
        for warehouse_id in permissions['warehouse_access']:
            
            warehouse = session.query(Warehouse).filter(Warehouse.id == warehouse_id).one()
            
            self.userWarehouseAddEditListstore.append([warehouse, warehouse.id, warehouse.name])
        
        self.userCategoryAddEditListstore.clear()
        for category_id in permissions['category_access']:
            
            category = session.query(Category).filter(Category.id == category_id).one()
            
            self.userCategoryAddEditListstore.append([category, category.id, category.name])
        
        # Viewing and Adding
        for k in self.di.keys():
            
            self.di[k].set_active(permissions[k])
        
        result = self.userAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.usWidgets) == -1:
            
            result = self.userAddEditDialog.run()
            
            self.reset_widgets(self.usWidgets, False)
            
        if (result == gtk.RESPONSE_OK):
            
            if self.password != self.userPasswordEntry.get_text():
                
                it.set_password(self.userPasswordEntry.get_text())
            
            self.userWarehouseSelectedList = []
            self.userCategorySelectedList = []
            
            _iter = self.userWarehouseAddEditListstore.get_iter_first()
            while _iter is not None:
            
                self.userWarehouseSelectedList.append(self.userWarehouseAddEditListstore.get_value(_iter, 0).id)
            
                _iter = self.userWarehouseAddEditListstore.iter_next(_iter)
        
            _iter = self.userCategoryAddEditListstore.get_iter_first()
            while _iter is not None:
            
                self.userCategorySelectedList.append(self.userCategoryAddEditListstore.get_value(_iter, 0).id)
            
                _iter = self.userCategoryAddEditListstore.iter_next(_iter)
        
            for k in self.di.keys():
                
                permissions[k] = self.di[k].get_active()
                
            permissions['warehouse_access'] = self.userWarehouseSelectedList
            permissions['category_access']  = self.userCategorySelectedList
                
            it.set_permissions(permissions)
            
            session.commit()
            self.reset_widgets(self.usWidgets)
            for k in self.di.keys():
                
                self.di[k].set_active(False)
        
        self.userAddEditDialog.hide()
        
    def on_inTreeview_row_activated(self, treeview, path, column):
        
        if not self.current_permissions["edit_inventory"]:
            
            return
        
        self.itemAddEditDialog.set_title(_("Edit Item Dialog"))
        
        inModel = treeview.get_model()
        inIter  = inModel.get_iter(path)
        
        m = inModel.get_value(inIter, 0)
        self.current_item = m
        
        self.itemNameEntry.set_text(m.name)
        
        self.set_combobox_value(self.itemUnitListstore, self.itemUnitCombobox, m.unit.name)
        self.set_combobox_value(self.itemCategoryListstore, self.itemCategoryCombobox, m.category.name)
        
        self.populate_inStockListstore(m.stocks)
        
        result = self.itemAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.itemWidgets) == -1:
            
            result = self.itemAddEditDialog.run()
            
            self.reset_widgets(self.itemWidgets, False)
            
        self.itemAddEditDialog.hide()
        
        if result == gtk.RESPONSE_OK:
            
            unit_name = self.get_combobox_value(self.itemUnitCombobox)
            unit = session.query(Unit).filter_by(name=unit_name).one()
            category_name = self.get_combobox_value(self.itemCategoryCombobox)
            category = session.query(Category).filter_by(name=category_name).one()
            
            m.name = self.itemNameEntry.get_text()
            m.unit_id = unit.id
            m.category_id = category.id
            
            m.stocks.clear()
            
            _iter = self.inStockListstore.get_iter_first()
            while _iter is not None:
            
                m.stocks.append(self.inStockListstore.get_value(_iter, 0))
            
                _iter = self.inStockListstore.iter_next(_iter)
            
            session.commit()
            
            self.inListstore.set(inIter, 
                0, m, 
                1, m.id,
                2, m.id,
                3, m.name,
                4, "%s %s" % (m.getStocks(self.current_permissions['warehouse_access']), m.unit.name))
            
        else:
            
            session.rollback()
            
        self.reset_widgets(self.itemWidgets)
        
    def on_maInWarehouseModifyButton_clicked(self, widget):
        
        self.maWarehouseManagementDialog.set_title(_("Warehouse Management"))
        
        result = self.maWarehouseManagementDialog.run()
        
        if (result == gtk.RESPONSE_OK):
            
            pass
        
        self.maWarehouseManagementDialog.hide()
    
    def on_maInCategoryModifyButton_clicked(self, widget):
        
        pass
    
    def on_maInUnitModifyButton_clicked(self, widget):
        
        self.maUnitManagementDialog.set_title(_("Unit Management"))
        
        result = self.maUnitManagementDialog.run()
        
        if (result == gtk.RESPONSE_OK):
            
            pass
        
        self.maUnitManagementDialog.hide()
        
    def on_maUsUserModifyButton_clicked(self, widget):
        
        self.maUserManagementDialog.set_title(_("User Management"))
        
        result = self.maUserManagementDialog.run()
        
        if (result == gtk.RESPONSE_OK):
            
            print
        
        self.maUserManagementDialog.hide()
        
    def on_maUsOperatorModifyButton_clicked(self, widget):
        
        self.maOperatorManagementDialog.set_title(_("Operator Management"))
        
        result = self.maOperatorManagementDialog.run()
        
        if (result == gtk.RESPONSE_OK):
            
            print
        
        self.maOperatorManagementDialog.hide()
        
    def on_eqTreeview_row_activated(self, treeview, path, column):
        
        if not self.current_permissions["edit_equipment"]:
            
            return
        
        self.itemAddEditDialog.set_title(_("Edit Equipment Dialog"))
        
        eqModel = treeview.get_model()
        eqIter  = eqModel.get_iter(path)
        
        eq = eqModel.get_value(eqIter, 0)
        
        self.eqEquipmentNumberEntry.set_text(eq.number)
        self.eqMakeEntry.set_text(eq.make)
        self.eqEngineNumberEntry.set_text(eq.engine_number)
        self.eqPlateNumberEntry.set_text(eq.plate_number)
        self.eqChassisNumberEntry.set_text(eq.chassis_number)
        self.eqRentalRateSpinButton.set_value(eq.rental_rate)
        self.eqRegistrationDate.set_date(eq.registration_date)
        
        # Set Combobox values
        self.set_combobox_value(self.eqEquipmentTypeListStore, self.eqEquipmentTypeCombobox, eq.equipment_type.name)
        self.set_combobox_value(self.eqUnitPriceListStore, self.eqUnitPriceCombobox, eq.equipment_unit.name)
        self.set_combobox_value(self.eqLTOStatusListStore, self.eqLTOStatusCombobox, eq.lto_status.name)
        self.set_combobox_value(self.eqAvailabilityStatusListStore, self.eqAvailabilityStatusCombobox, eq.equipment_status.name)
        
        result = self.eqAddEditDialog.run()
        
        while result == gtk.RESPONSE_OK and \
              self.validate_widgets(self.eqWidgets, self.eqAddEditNotebook) == -1:
            
            result = self.eqAddEditDialog.run()
            
            self.reset_widgets(self.eqWidgets, False, self.eqAddEditNotebook)
            
        self.eqAddEditDialog.hide()
        
        if result == gtk.RESPONSE_OK:
            
            eq = self.eqPerformEdit(eq)
            
            self.eqListstore.set(eqIter, 
                0, eq, 
                1, eq.id, 
                2, eq.number, 
                3, eq.equipment_type.name, 
                4, eq.make, 
                5, eq.engine_number, 
                6, eq.plate_number, 
                7, eq.chassis_number, 
                8, "%.2f / %s" % (eq.rental_rate, eq.equipment_unit.name), 
                9, eq.lto_status.name, 
                10, eq.equipment_status.name, )
            
        else:
            
            session.rollback()
        
        self.reset_widgets(self.eqWidgets, notebook=self.eqAddEditNotebook)
        
    def on_inTreeview_cursor_changed(self, widget):
        
        #return
        
        selected_row = widget.get_selection().get_selected_rows()
        inModel      = widget.get_model()
        
        try:
            
            _iter = self.inListstore.get_iter(selected_row[1][0])
            path  = inModel.get_path(_iter)
        
            self.c_context_id = self.m_context_id
        
            self.statusbar.pop(self.m_context_id)
            self.statusbar.push(self.m_context_id, _("Particular: %s") % inModel[path][3])
        
        except IndexError:
            
            pass
        
    def on_mainTreeview_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 46 or (event.hardware_keycode == 22 and sys.platform == "linux2"):
            
            model = widget.get_model()
            selected = widget.get_selection().get_selected()
            
            if selected[1] == None:
                
                return
            
            row = selected[0][selected[1]]
            
            instance = row[0]
            
            ## Show warning dialog here
            markup = "<b><big>Are you sure you want to delete the selected item?</big></b>"
            secondary_markup = "All information on this expense entry will be deleted and can not be restored."
            self.warningMessageDialog.set_markup(markup)
            self.warningMessageDialog.format_secondary_markup(secondary_markup)
            
            result = self.warningMessageDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                session.commit()
                
                model.remove(selected[1])
                
            self.warningMessageDialog.hide()
        
    def on_eqTreeview_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 46 or (event.hardware_keycode == 22 and sys.platform == "linux2"):
            
            model = widget.get_model()
            selected = widget.get_selection().get_selected()
            
            if selected[1] == None:
                
                return
            
            row = selected[0][selected[1]]
            
            instance = row[0]
            
            markup = "<b><big>Are you sure you want to delete the equipment '%s'?</big></b>" % instance.number
            secondary_markup = "All information on this equipment will be deleted and can not be restored."
            self.warningMessageDialog.set_markup(markup)
            self.warningMessageDialog.format_secondary_markup(secondary_markup)
            result = self.warningMessageDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                equipment_id = instance.id
                
                for expense in session.query(Expense).filter(Expense.equipment_id==equipment_id):
                    
                    session.delete(expense)
                
                session.delete(instance)
                session.commit()
                
                model.remove(selected[1])
                
            self.warningMessageDialog.hide()
            
    def on_exTreeview_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 46 or (event.hardware_keycode == 22 and sys.platform == "linux2"):
            
            model = widget.get_model()
            selected = widget.get_selection().get_selected()
            
            if selected[1] == None:
                
                return
            
            row = selected[0][selected[1]]
            
            instance = row[0]
            
            ## Show warning dialog here
            markup = "<b><big>Are you sure you want to delete the expense entry '%s'?</big></b>" % instance.po_number
            secondary_markup = "All information on this expense entry will be deleted and can not be restored."
            self.warningMessageDialog.set_markup(markup)
            self.warningMessageDialog.format_secondary_markup(secondary_markup)
            
            result = self.warningMessageDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                for purchase in instance.purchases:
                    
                    session.delete(purchase)
                    
                for repair in instance.repairs:
                    
                    session.delete(repair)
                    
                for salary in instance.salaries:
                    
                    session.delete(salary)
                    
                session.delete(instance)
                
                session.commit()
                
                model.remove(selected[1])
                
            self.warningMessageDialog.hide()
        
    def on_inTreeview_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 46 or (event.hardware_keycode == 22 and sys.platform == "linux2"):
            
            model = widget.get_model()
            selected = widget.get_selection().get_selected()
            
            if selected[1] == None:
                
                return
            
            row = selected[0][selected[1]]
            
            instance = row[0]
            
            ## Show warning dialog here
            markup = "<b><big>Are you sure you want to delete the inventory item '%s'?</big></b>" % instance.name
            secondary_markup = "All information on this inventory item will be deleted and can not be restored."
            self.warningMessageDialog.set_markup(markup)
            self.warningMessageDialog.format_secondary_markup(secondary_markup)
            result = self.warningMessageDialog.run()
            
            if result == gtk.RESPONSE_OK:
                
                #for stock in instance.stocks:
                #    
                #    session.delete(stock)
                    
                session.delete(instance)
                
                session.commit()
                
                model.remove(selected[1])
                
            self.warningMessageDialog.hide()
            
            #print session.query(Cast).filter(Cast.full_name=="Daniel Craig").count()
            
        pass
    
    def on_cuCountryCombobox_changed(self, widget):
        
        model = widget.get_model()
        active = widget.get_active()
        
        country = model[active][0]
        
        if country == _("Select one"):
            
            self.cuCityCombobox.set_sensitive(False)
            self.cuStateCombobox.set_sensitive(False)
            
        else:
            
            self.cuStateCombobox.set_sensitive(True)
            c = session.query(Country).filter(Country.name==country).one()
            self.populate_cuStateCombobox(c.id)
            
    def on_inCategoryCombobox_changed(self, widget):
        
        self.on_inFindButton_clicked(self)
        
    def on_exEqUnitCombobox_changed(self, widget):
        
        model = widget.get_model()
        active = widget.get_active()
        
        if active < 0:
            
            return
        
        equipment_number = model[active][0]
        
        if equipment_number != _("Select one"):
            
            eq = session.query(Equipment).filter(Equipment.number==equipment_number).one()
            self.exEqPlateLabelValue.set_text(eq.plate_number)
            
        else:
            
            self.exEqPlateLabelValue.set_text("")
            
        self.exExPONumberEntry.grab_focus()
        
    def on_exQuantitySpinbutton_value_changed(self, widget):
        
        self.exAddPurchaseButton.set_sensitive(widget.get_value_as_int() > 0)
        
    def on_exItemCombobox_changed(self, widget):
        
        model = widget.get_model()
        active = widget.get_active()
        
        if active < 0:
            
            return
        
        item_name = model[active][0]
        
        if item_name != _("Select one"):
            
            item = session.query(Item).filter(Item.name==item_name).one()
            
            self.exUnitLabel.set_text(item.unit.name)
            
            self.exQuantitySpinbutton.set_range(0, item.getStocks(self.current_permissions['warehouse_access']))
            self.exQuantitySpinbutton.set_increments(1, 1)
            self.exQuantitySpinbutton.set_sensitive(True)
            
        else:
            
            self.exQuantitySpinbutton.set_range(0, 0)
            self.exQuantitySpinbutton.set_sensitive(False)
            
    def on_reportTypeCombobox_changed(self, widget):
        
        self.on_reportFindButton_clicked(self)
            
    def on_eqTypeCombobox_changed(self, widget):
        
        self.on_eqFindButton_clicked(self)
        
    def on_cuStateCombobox_changed(self, widget):
        
        model = widget.get_model()
        active = widget.get_active()
        
        if active != -1:
            
            state = model[active][0]
        
            if state == _("Select one"):
                
                self.cuCityCombobox.set_sensitive(False)
                
            else:
                
                self.cuCityCombobox.set_sensitive(True)
                
                s = session.query(StateCity).filter(StateCity.name==state).one()
                self.populate_cuCityCombobox(s.id)
        
    def on_cuTreeview_row_activated(self, treeview, path, column):
        
        return
        
    def on_reCuTreeview_row_activated(self, treeview, path, column):
        
        reCuModel = treeview.get_model()
        reCuIter = reCuModel.get_iter(path)
        
        customer = reCuModel.get_value(reCuIter, 0)
        
        self.rePerformRental(customer)
        
    def on_reCuEntry_key_press_event(self, widget, event):
        
        self.reCuCode = self.builder.get_object("reCuCode")
        self.reCuName = self.builder.get_object("reCuName")
        self.reCuAddress = self.builder.get_object("reCuAddress")
        self.reCuAddress2 = self.builder.get_object("reCuAddress2")
        self.reCuCity = self.builder.get_object("reCuCity")
        self.reCuState = self.builder.get_object("reCuState")
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            string = self.reCuEntry.get_text()
            self.reCuListstore.clear()
            
            try:
                
                customer = session.query(Customer).filter(Customer.id==string).one()
                
            except NoResultFound:
                
                regex = re.compile("%s" % string, re.IGNORECASE)
                
                customerList = []
                for customer in session.query(Customer):
                    
                    if (regex.search(customer.first_name) or regex.search(customer.last_name) \
                       or regex.search(customer.middle_name) or regex.search(customer.street) \
                       or regex.search(str(customer.id))) and customer not in customerList:
                        
                        customerList += [customer]
                        
                self.update_reCuListstore(customerList)
                self.reCuTreeview.set_headers_visible(True)
                
                return
                
            self.rePerformRental(customer)
            
    def on_reInEntry_key_press_event(self, widget, event):
        
        if event.hardware_keycode == 13 or \
           (event.hardware_keycode == 36 and platform.system() == 'Darwin'):
            
            string = self.reInEntry.get_text()
            self.reInEntry.set_text("")
            
            try:
                
                movie = session.query(Movie).filter(Movie.id==string).one()
                
            except NoResultFound:
                
                notice = _("Movie code %s isn't in the database.") % string
                
                self.reInAlertLabel.set_label("<span foreground='red'>%s</span>" % notice)
                return
            
            if not self.in_movie_list(movie, self.reInListstore):
                
                self.update_reInListstore([movie])
                
            self.reInTreeview.set_headers_visible(True)
            
    def on_inShowAllButton_clicked(self, widget):
        
        self.inEntry.set_text("")
        self.inEntry.grab_focus()
        
        if hasattr(self, 'inCategoryListstore'):
            
            self.inCategoryCombobox.set_active(0)
        
        itemList = []
        for item in session.query(Item).filter(Item.category_id.in_(self.current_permissions['category_access'])):
            
            itemList += [item]
            
        self.inListstore.clear()
        self.update_inListstore(itemList)
        
    def on_eqShowAllButton_clicked(self, widget):
        
        self.eqEntry.set_text("")
        self.eqEntry.grab_focus()
        
        if hasattr(self, 'eqTypeListstore'):
            
            self.eqTypeCombobox.set_active(0)
        
        equipmentList = []
        for equipment in session.query(Equipment).order_by(Equipment.id):
            
            equipmentList += [equipment]
            
        self.eqListstore.clear()
        self.update_eqListstore(equipmentList)
        
    def on_reportShowAllButton_clicked(self, widget):
        
        self.reportEntry.set_text("")
        self.reportEntry.grab_focus()
        
        if hasattr(self, 'reportEquipmentTypeListStore'):
            
            self.reportTypeCombobox.set_active(0)
        
        equipmentList = []
        for equipment in session.query(Equipment).order_by(Equipment.id):
            
            equipmentList += [equipment]
            
        self.populate_reListstore(equipmentList)
        
    def on_exShowAllButton_clicked(self, widget):
        
        self.exEntry.set_text("")
        self.exListstore.clear()
        self.exEntry.grab_focus()
        
        exList = []
        for ex in session.query(Expense):
            
            if ex not in exList:
                
                exList += [ex]
                
                self.update_exListstore(ex)
        
    def on_inFindButton_clicked(self, widget):
        
        #self.set_cursor("watch")
        
        searchString  = self.inEntry.get_text()
        
        self.inListstore.clear()
        self.inEntry.grab_focus()
        
        regex = re.compile(re.escape(searchString), re.IGNORECASE)
            
        itemList = []
        
        if hasattr(self, 'inCategoryListstore'):
            
            category = self.get_combobox_value(self.inCategoryCombobox)
            
            # filter by search string and by category
            if category != _("All Categories"):
                
                category = session.query(Category).filter(Category.name==category).one()
            
                for item in session.query(Item).filter(and_(Item.category_id.in_(self.current_permissions['category_access']), Item.category_id==category.id)).order_by(Item.id):
                
                    if regex.search(item.name):
                        
                        itemList += [item]
                        
            # filter by search string only since "All Categories" was selected
            else:
                
                for item in session.query(Item).filter(Item.category_id.in_(self.current_permissions['category_access'])).order_by(Item.id):
                
                    if regex.search(item.name):
                    
                        itemList += [item]
        else:
            
            for item in session.query(Item).filter(Item.category_id.in_(self.current_permissions['category_access'])).order_by(Item.id):
                
                if regex.search(item.name):
                    
                    itemList += [item]
                
        self.update_inListstore(itemList)
        
        #self.root_window.set_cursor(None)
        
    def on_eqFindButton_clicked(self, widget):
        
        #self.set_cursor("watch")
        
        searchString  = self.eqEntry.get_text()
        
        self.eqListstore.clear()
        self.eqEntry.grab_focus()
        
        regex = re.compile(re.escape(searchString), re.IGNORECASE)
            
        equipmentList = []
        
        if hasattr(self, 'eqTypeListstore'):
            
            eq_type = self.get_combobox_value(self.eqTypeCombobox)
            
            # filter by search string and by category
            if eq_type != _("All Equipment Types"):
                
                eq_type = session.query(EquipmentType).filter(EquipmentType.name==eq_type).one()
            
                for equipment in session.query(Equipment).filter(Equipment.type_id==eq_type.id).order_by(Equipment.id):
                
                    if regex.search(equipment.number):
                        
                        equipmentList += [equipment]
                        
            # filter by search string only since "All Equipment Types" was selected
            else:
                
                for equipment in session.query(Equipment).order_by(Equipment.id):
                
                    if regex.search(equipment.number):
                    
                        equipmentList += [equipment]
        else:
            
            for equipment in session.query(Equipment).order_by(Equipment.id):
                
                if regex.search(equipment.number):
                    
                    equipmentList += [equipment]
                
        self.update_eqListstore(equipmentList)
        
        #self.root_window.set_cursor(None)
        
    def on_reportFindButton_clicked(self, widget):
        
        #self.set_cursor("watch")
        
        searchString  = self.reportEntry.get_text()
        
        self.reportEntry.grab_focus()
        
        regex = re.compile(re.escape(searchString), re.IGNORECASE)
            
        equipmentList = []
        
        if hasattr(self, 'reportEquipmentTypeListStore'):
            
            eq_type = self.get_combobox_value(self.reportTypeCombobox)
            
            # filter by search string and by category
            if eq_type != _("All Equipment Types"):
                
                eq_type = session.query(EquipmentType).filter(EquipmentType.name==eq_type).one()
            
                for equipment in session.query(Equipment).filter(Equipment.type_id==eq_type.id).order_by(Equipment.id):
                
                    if regex.search(equipment.number):
                        
                        equipmentList += [equipment]
                        
            # filter by search string only since "All Equipment Types" was selected
            else:
                
                for equipment in session.query(Equipment).order_by(Equipment.id):
                
                    if regex.search(equipment.number):
                    
                        equipmentList += [equipment]
        else:
            
            for equipment in session.query(Equipment).order_by(Equipment.id):
                
                if regex.search(equipment.number):
                    
                    equipmentList += [equipment]
                
        self.populate_reListstore(equipmentList)
        
        #self.root_window.set_cursor(None)
        
    def on_exFindButton_clicked(self, widget):
        
        #self.set_cursor("watch")
        
        searchTitle = self.exEntry.get_text()
        
        self.exListstore.clear()
        self.exEntry.grab_focus()
        
        if searchTitle == "":
            
            self.on_exShowAllButton_clicked(widget)
            
            return
        
        else:
            
            regex = re.compile("%s" % searchTitle, re.IGNORECASE)
            
        exList = []
        for ex in session.query(Expense):
            
            if regex.search(ex.po_number) and ex not in exList:
                
                exList += [ex]
                
                self.update_exListstore(ex)
                
        
        
        #self.root_window.set_cursor(None)
        
    def on_exSalaryAddButton_clicked(self, widget):
        
        self.expenseAddEditDialog.set_title(_("Salary Dialog"))
        
        self.exExExFrame.hide()
        self.exExItFrame.hide()
        self.exExReFrame.hide()
        self.exExSaFrame.show()
        
        result = self.expenseAddEditDialog.run()
        while result == gtk.RESPONSE_OK and (self.validate_widgets(self.exSaWidgets) == -1):
            
            result = self.expenseAddEditDialog.run()
            
        if (result == gtk.RESPONSE_OK):
            
            eqModel = self.exEqUnitCombobox.get_model()
            eqActive = self.exEqUnitCombobox.get_active()
            
            eq_number = eqModel[eqActive][0]
            eq = session.query(Equipment).filter(Equipment.number==eq_number).one()
            date = self.exExSaDate.get_date()
            
            opModel = self.exExSaOperatorCombobox.get_model()
            opActive = self.exExSaOperatorCombobox.get_active()
            
            op_full_name = opModel[opActive][0]
            op = op_full_name.split(", ")
            op_obj = session.query(Operator).filter(and_(Operator.first_name==op[1], Operator.last_name==op[0])).one()
            
            operator_id = op_obj.id
            amount = self.exExSaAmountSpinbutton.get_value_as_int()
            remarks = self.exExSaRemarksEntry.get_text()
            
            expense = Expense(date, "N/A", eq.id)
            
            s = Salary(operator_id, amount, remarks)
            
            expense.salaries.append(s)
                
            session.add(expense)
            session.commit()
            
            self.update_exListstore(expense)
            
        self.expenseAddEditDialog.hide()
        
    def on_exRepairAddButton_clicked(self, widget):
        
        self.expenseAddEditDialog.set_title(_("Repair / Maintenance Dialog"))
        
        self.exExExFrame.hide()
        self.exExItFrame.hide()
        self.exExReFrame.show()
        self.exExSaFrame.hide()
        
        result = self.expenseAddEditDialog.run()
        while result == gtk.RESPONSE_OK and (self.validate_widgets(self.exReWidgets) == -1):
            
            result = self.expenseAddEditDialog.run()
            
        if (result == gtk.RESPONSE_OK):
            
            eqModel = self.exEqUnitCombobox.get_model()
            eqActive = self.exEqUnitCombobox.get_active()
            
            eq_number = eqModel[eqActive][0]
            eq = session.query(Equipment).filter(Equipment.number==eq_number).one()
            date = self.exExReDate.get_date()
            
            scope = self.exExReScopeEntry.get_text()
            labor = self.exExReLaborSpinbutton.get_value_as_int()
            service = self.exExReServiceEntry.get_text()
            
            expense = Expense(date, "N/A", eq.id)
            
            r = Repair(scope, labor, service)
            
            expense.repairs.append(r)
                
            session.add(expense)
            session.commit()
            
            self.update_exListstore(expense)
            
        self.expenseAddEditDialog.hide()
        
    def on_exAddButton_clicked(self, widget):
        
        self.expenseAddEditDialog.set_title(_("Add Expense Dialog"))
        
        self.exExExFrame.show()
        self.exExItFrame.show()
        self.exExReFrame.hide()
        self.exExSaFrame.hide()
        
        result = self.expenseAddEditDialog.run()
        while result == gtk.RESPONSE_OK and (self.validate_widgets(self.exWidgets) == -1 \
              or len(self.exItListstore) == 0):
            
            result = self.expenseAddEditDialog.run()
            
        if (result == gtk.RESPONSE_OK):
            
            #session.commit()
            
            eqModel = self.exEqUnitCombobox.get_model()
            eqActive = self.exEqUnitCombobox.get_active()
            
            eq_number = eqModel[eqActive][0]
            eq = session.query(Equipment).filter(Equipment.number==eq_number).one()
            date = self.exExDate.get_date()
            po_number = self.exExPONumberEntry.get_text()
            
            expense = Expense(date, po_number, eq.id)
            
            for stock in self.exItList:
                
                p = Purchase(stock[0].id, stock[1])
                expense.purchases.append(p)
                
            session.add(expense)
            session.commit()
            
            self.update_exListstore(expense)
            
        else:
            
            session.rollback()
            
        self.expenseAddEditDialog.hide()
        self.reset_widgets(self.exWidgets)
        self.exItListstore.clear()
        self.exItList = []
        self.exTotalLabelValue.set_text("0.00")
        
    def on_reButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        # clear the liststore
        self.reCuListstore.clear()
        self.reInListstore.clear()
        
        self.reCuEntry.grab_focus()
        
        # set some attributes
        self.notebook.set_current_page(0)
        self.reNotebook.set_current_page(0)
        self.reCuEntry.set_text("")
        self.reInEntry.set_text("")
        self.reInAlertLabel.set_label("")
        self.reCuTreeview.set_headers_visible(False)
        
    def on_inButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.notebook.set_current_page(1)
        self.reNotebook.set_current_page(0)
        
        self.inEntry.set_activates_default(True)
        self.inEntry.grab_focus()
        
        self.inFindButton.grab_default()
        
        self.on_inFindButton_clicked(widget)
        
    def on_cuButton_clicked(self, widget):
        
        self.populate_exItemListStore()
        self.populate_exUnitListStore()
        self.populate_exOperatorListStore()
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.notebook.set_current_page(2)
        self.reNotebook.set_current_page(0)
        
        self.exEntry = self.builder.get_object("exEntry")
        self.exFindButton = self.builder.get_object("exFindButton")
        
        self.exEntry.set_activates_default(True)
        self.exEntry.grab_focus()
        
        self.on_exShowAllButton_clicked(self)
        
        self.exFindButton.grab_default()
        
    def on_trButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.notebook.set_current_page(3)
        self.reNotebook.set_current_page(0)
        
        self.eqEntry.set_activates_default(True)
        self.eqEntry.grab_focus()
        
        self.eqFindButton.grab_default()
        
        self.on_eqFindButton_clicked(widget)
        
    def on_rpButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.reportEntry.set_activates_default(True)
        self.reportEntry.grab_focus()
        
        self.reportFindButton.grab_default()
            
        self.notebook.set_current_page(4)
        self.reNotebook.set_current_page(0)
        
        self.populate_reListstore()
        
    def on_maButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.notebook.set_current_page(5)
        self.reNotebook.set_current_page(0)
        
    def on_daButton_clicked(self, widget):
        
        if self.c_context_id != self.context_id:
            
            self.statusbar.pop(self.c_context_id)
            
        self.notebook.set_current_page(6)
        self.reNotebook.set_current_page(0)
        
    def on_menuButton_clicked(self, widget):
        
        label = widget.get_label()
        
        buttonDict = {
            _("_Rentals"):0, _("_Inventory"):1, _("_Customers"):2, 
            _("E_quipment"):3, _("Rep_orts"):4, _("_Maintenance"):5, 
            _("_Day-End"):6
        }
        
        self.notebook.set_current_page(buttonDict[label])
        
        if label == _("_Customers"):
            
            self.cuEntry = self.builder.get_object("cuEntry")
            self.cuFindButton = self.builder.get_object("cuFindButton")
            
            self.cuEntry.set_activates_default(True)
            self.cuEntry.grab_focus()
            
            self.cuFindButton.grab_default()
            
    def on_reQueryButton_clicked(self, widget):
        
        from_date = self.reFromDate.get_date()
        to_date   = self.reToDate.get_date()
        
        self.populate_reReportListstore(self.reSummaryPartsLabel, self.rePartsListstore, self.rePartsTotalLabel, 2, from_date, to_date)
        self.populate_reReportListstore(self.reSummaryFuelLabel, self.reFuelListstore, self.reFuelTotalLabel, 1, from_date, to_date)
        self.populate_reRepairListstore(from_date, to_date)
        self.populate_reSalaryListstore(from_date, to_date)
        #print self.get_total_expense_by_category(self.equipment.id, 2, from_date, to_date)
        
        pass
            
    def on_exAddPurchaseButton_clicked(self, widget):
        
        model = self.exItemCombobox.get_model()
        active = self.exItemCombobox.get_active()
        
        item_name = model[active][0]
        
        item      = session.query(Item).filter(Item.name==item_name).one()
        unit_name = item.unit.name
        required_quantity  = self.exQuantitySpinbutton.get_value_as_int()
        stockList = item.getStockList(self.current_permissions["warehouse_access"])
        
        for stock in stockList:
            
            stock_on_hand = stock.credit - stock.debit
            
            if required_quantity > stock_on_hand:
                
                self.update_exItListstore(stock, stock_on_hand, item_name, unit_name)
                self.exItList.append([stock, stock_on_hand, item_name, unit_name])
                
                required_quantity = required_quantity - stock_on_hand
                stock.debit = stock.debit + stock_on_hand
                
            else:
                
                self.update_exItListstore(stock, required_quantity, item_name, unit_name)
                self.exItList.append([stock, required_quantity, item_name, unit_name])
                
                stock.debit = stock.debit + required_quantity
                required_quantity = 0
                
                break
        
        self.exItemCombobox.set_active(0)
        
    #***************************************************************************
    # Methods
    #***************************************************************************
    def convert_listToStr(self, li):
        
        string = ""
        for l in li:
            
            string += l.name
            
            if l != li[-1]:
                
                string += ", "
                
        return string
    
    def reset_widgets(self, widgetsList, value=True, notebook=None):
        
        for w in widgetsList:
            
            widget = w[0]
            label  = w[1]
            text   = w[2]
            
            if notebook:
                
                notebook.set_current_page(0)
                
            label.set_markup_with_mnemonic("%s" % text)
            
            if value:
                
                widget.set_sensitive(w[3])
                
                if isinstance(widget, gtk.Entry):
                    
                    widget.set_text("")
                    
                elif isinstance(widget, gtk.ComboBox):
                    
                    widget.set_active(0)
                    
                elif isinstance(widget, gtk.TreeView):
                    
                    model = widget.get_model()
                    model.clear()
                    
                    entries = {
                        "inGenresAddEditListstore"  : self.inGenresEntry,
                        "inCastsAddEditListstore"   : self.inCastsEntry,
                        "inWritersAddEditListstore" : self.inWritersEntry
                    }
                    
                    entry = entries[model.get_name()]
                    
                    if entry:
                        
                        entry.set_text("")
                        
                    widget.get_selection().unselect_all()
                    
                elif isinstance(widget, gtk.SpinButton):
                    
                    widget.set_value(0.0)
                    
    def validate_widgets(self, widgetsList, notebook=None):
        
        """Widget Validator
        Validates all the widgets from the widgetList for possible errors.
        """
        
        types = (gtk.Entry, gtk.ComboBox, gtk.TreeView, gtk.SpinButton)
        
        ret_value = 0
        
        for w in widgetsList:
            
            widget = w[0]
            label  = w[1]
            text   = w[2]
            
            if notebook:
                
                notebook.set_current_page(w[4])
                
            ## If widget is a gtk.Entry
            if isinstance(widget, types[0]):
                
                ## If widget is a gtk.SpinButton
                if hasattr(widget, "get_value_as_int"):
                    
                    if widget.get_value_as_int() == 0:
                        
                        label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)
                        
                        widget.grab_focus()
                        
                        ret_value = -1
                        
                        break
            
                if widget.get_text() == "":
                    
                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)
                    
                    widget.grab_focus()
                    
                    ret_value = -1
                    
                    break
                
                label.set_markup_with_mnemonic("%s" % text)
                
            ## If widget is a gtk.ComboBox
            elif isinstance(widget, types[1]):
                
                model  = widget.get_model()
                active = widget.get_active()
                
                if model[active][0] == _("Select one"):
                    
                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)
                    
                    widget.grab_focus()
                    
                    ret_value = -1
                    
                    break
                
                else:
                    
                    label.set_markup_with_mnemonic("%s" % text)
                    
            ## If widget is a gtk.TreeView
            elif isinstance(widget, types[2]):
                
                entries = {
                    "inGenresAddEditListstore"  : self.inGenresEntry,
                    "inCastsAddEditListstore"   : self.inCastsEntry,
                    "inWritersAddEditListstore" : self.inWritersEntry
                }
                
                model = widget.get_model()
                
                if not model:
                    
                    entry = entries[model.get_name()]
                    
                    if entry:
                        
                        entry.grab_focus()
                        
                    label.set_markup_with_mnemonic("<span style='italic' foreground='red'>%s</span>" % text)
                    
                    ret_value = -1
                    
                    break
                
                else:
                    
                    label.set_markup_with_mnemonic("%s" % text)
                    
        return ret_value
    
    def in_movie_list(self, movie, liststore):
        
        """Checks if the movie object is in the liststore."""
        
        _iter = liststore.get_iter_first()
        return_val = False
        
        self.reInAlertLabel.set_label("")
        
        while _iter is not None:
            
            m = liststore.get_value(_iter, 0)
            
            if m != movie:
                
                pass
            
            elif m == movie:
                
                return_val = True
                self.reInAlertLabel.set_label("<span foreground='red'>%s is already in the list.</span>" % m.title)
                
            elif m.status != 2:
                
                return_val = True
                
            elif m.status == 2:
                
                return_val = True
                self.reInAlertLabel.set_label("<span foreground='red'>%s has already been rented.</span>" % m.title)
                
            _iter = liststore.iter_next(_iter)
            
        return return_val
    
    def get_total_salary_expense(self, equipment_id):
        
        d = datetime.datetime.now()
        days_in_a_month = calendar.mdays[datetime.date.today().month]
        
        fr = "%s-%s-01" % (d.year, d.month)
        to = "%s-%s-%s" % (d.year, d.month, days_in_a_month)
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==equipment_id, 
            Expense.date >= (fr), 
            Expense.date <= (to))).order_by(Expense.id):
            
            for salary in ex.salaries:
                
                total += salary.amount
                
        return total
    
    def get_total_repair_expense(self, equipment_id):
        
        d = datetime.datetime.now()
        days_in_a_month = calendar.mdays[datetime.date.today().month]
        
        fr = "%s-%s-01" % (d.year, d.month)
        to = "%s-%s-%s" % (d.year, d.month, days_in_a_month)
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==equipment_id, 
            Expense.date >= (fr), 
            Expense.date <= (to))).order_by(Expense.id):
            
            for repair in ex.repairs:
                
                total += repair.labor
                
        return total
    
    def get_total_expense_by_category(self, eq_id, category_id, fr=None, to=None):
        
        category = session.query(Category).filter(Category.id==category_id).one()
        
        d = datetime.datetime.now()
        days_in_a_month = calendar.mdays[datetime.date.today().month]
        
        if fr == None:
            
            fr = "%s-%s-01" % (d.year, d.month)
            
        if to == None:
            
            to = "%s-%s-%s" % (d.year, d.month, days_in_a_month)
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==eq_id, 
            Expense.date >= (fr), 
            Expense.date <= (to))).order_by(Expense.id):
            
            for purchase in ex.purchases:
                
                stock = session.query(Stock).filter(Stock.id==purchase.stock_id).one()
                
                if stock.items[0].category_id==category.id:
                    
                    total += purchase.quantity * stock.unit_price
                    
        return total
    
    def get_combobox_value(self, combobox):
        
        model  = combobox.get_model()
        active = combobox.get_active()
        
        return model[active][0]
    
    def set_combobox_value(self, liststore, combobox, value):
        
        _iter = liststore.get_iter_first()
        while _iter is not None:
            
            if value == liststore.get_value(_iter, 0):
                
                path = liststore.get_path(_iter)
                
                combobox.set_active(path[0])
                
                break
            
            _iter = liststore.iter_next(_iter)
    
    def cuPerformEdit(self, cust):
        
        """
        Performs the actual customer edit. This method updates both GUI 
        and the database.
        """
        
        #self.set_cursor("watch")
        
        gender = {_("Male"):1, _("Female"):2}
        
        gnModel = self.cuGenderCombobox.get_model()
        gnActive = self.cuGenderCombobox.get_active()
        ciModel = self.cuCityCombobox.get_model()
        ciActive = self.cuCityCombobox.get_active()
        saModel = self.cuStateCombobox.get_model()
        saActive = self.cuStateCombobox.get_active()
        coModel = self.cuCountryCombobox.get_model()
        coActive = self.cuCountryCombobox.get_active()
        
        cust.last_name = self.cuLastnameEntry.get_text()
        cust.first_name = self.cuFirstnameEntry.get_text()
        cust.middle_name = self.cuMiddlenameEntry.get_text()
        cust.full_name = "%s, %s %s." % \
            (cust.last_name, cust.first_name, cust.middle_name[0])
        cust.street = self.cuStreetEntry.get_text()
        cust.zip_code = self.cuZipcodeEntry.get_text()
        cust.contact_number = PREFIX + self.cuContactnumberEntry.get_text()
        cust.gender = gender[gnModel[gnActive][0]]
        ci = ciModel[ciActive][0]
        sa = saModel[saActive][0]
        co = coModel[coActive][0]
        
        cust = insertCustomer(session, cust, ci, sa, co)
        
        #self.root_window.set_cursor(None)
        
        return cust
    
    def inPerformEdit(self, movie):
        
        """
        Performs the actual inventory edit. This method updates both GUI 
        and the database.
        """
        
        #self.set_cursor("watch")
        
        movie.title    = self.inTitleEntry.get_text()
        movie.imdbCode = self.inImdbCodeEntry.get_text()
        movie.release  = str(self.inReleaseCalendar.get_date())
        movie.plot     = self.inPlotEntry.get_text()
        movie.rating   = self.inRatingSpin.get_value()
        movie.rent     = self.inRentalCostSpin.get_value()
        movie.allotted = self.inAllottedDaysSpin.get_value()
        movie.status   = self.inStatusCombobox.get_active()
        
        self.inGenresSelectedList = []
        self.inCastsSelectedList = []
        self.inWritersSelectedList = []
        
        try:
            
            director = session.query(Director).filter(Director.full_name==self.inDirectorEntry.get_text()).one()
            
        except NoResultFound:
            
            director = Director(self.inDirectorEntry.get_text())
            
            ## TODO: Error here
            self.inDirectorListstore.append([director.full_name])
            
        # selected genres
        _iter = self.inGenresAddEditListstore.get_iter_first()
        while _iter is not None:
            
            self.inGenresSelectedList.append(self.inGenresAddEditListstore.get_value(_iter, 0))
            
            _iter = self.inGenresAddEditListstore.iter_next(_iter)
            
        # selected casts
        _iter = self.inCastsAddEditListstore.get_iter_first()
        while _iter is not None:
            
            self.inCastsSelectedList.append(self.inCastsAddEditListstore.get_value(_iter, 0))
            
            _iter = self.inCastsAddEditListstore.iter_next(_iter)
            
        # selected writers
        _iter = self.inWritersAddEditListstore.get_iter_first()
        while _iter is not None:
            
            self.inWritersSelectedList.append(self.inWritersAddEditListstore.get_value(_iter, 0))
            
            _iter = self.inWritersAddEditListstore.iter_next(_iter)
            
        movie.director = director
        movie.writers = self.inWritersSelectedList
        movie.casts = self.inCastsSelectedList
        movie.genres = self.inGenresSelectedList
        
        session.add(movie)
        session.commit()
        
        #self.root_window.set_cursor(None)
        
        return movie
    
    def eqPerformEdit(self, equipment):
        
        """
        Performs the actual inventory edit. This method updates both GUI 
        and the database.
        """
        
        #self.set_cursor("watch")
        
        eqType               = self.get_combobox_value(self.eqEquipmentTypeCombobox)
        eqUnitPrice          = self.get_combobox_value(self.eqUnitPriceCombobox)
        eqLTOStatus          = self.get_combobox_value(self.eqLTOStatusCombobox)
        eqAvailabilityStatus = self.get_combobox_value(self.eqAvailabilityStatusCombobox)
        
        eqType = session.query(EquipmentType).filter_by(name=eqType).one()
        eqUnitPrice = session.query(EquipmentUnit).filter_by(name=eqUnitPrice).one()
        eqLTOStatus = session.query(LTOStatus).filter_by(name=eqLTOStatus).one()
        eqAvailabilityStatus = session.query(EquipmentStatus).filter_by(name=eqAvailabilityStatus).one()
        
        equipment.number            = self.eqEquipmentNumberEntry.get_text()
        equipment.make              = self.eqMakeEntry.get_text()
        equipment.engine_number     = self.eqEngineNumberEntry.get_text()
        equipment.plate_number      = self.eqPlateNumberEntry.get_text()
        equipment.chassis_number    = self.eqChassisNumberEntry.get_text()
        equipment.rental_rate       = self.eqRentalRateSpinButton.get_value()
        equipment.registration_date = self.eqRegistrationDate.get_date()
        equipment.type_id           = eqType.id
        equipment.unit_id           = eqUnitPrice.id
        equipment.lto_status_id     = eqLTOStatus.id
        equipment.status_id         = eqAvailabilityStatus.id
        
        session.add(equipment)
        session.commit()
        
        #self.root_window.set_cursor(None)
        
        return equipment
    
    def eqPerformAdd(self):
        
        eqNumber = self.eqEquipmentNumberEntry.get_text()
        eqType   = self.get_combobox_value(self.eqEquipmentTypeCombobox)
        eqMake   = self.eqMakeEntry.get_text()
        eqEngineNumber = self.eqEngineNumberEntry.get_text()
        eqPlateNumber = self.eqPlateNumberEntry.get_text()
        eqChassisNumber = self.eqChassisNumberEntry.get_text()
        eqRentalRate = self.eqRentalRateSpinButton.get_value_as_int()
        eqUnitPrice = self.get_combobox_value(self.eqUnitPriceCombobox)
        eqLTOStatus = self.get_combobox_value(self.eqLTOStatusCombobox)
        eqAvailabilityStatus = self.get_combobox_value(self.eqAvailabilityStatusCombobox)
        eqRegistrationDate = self.eqRegistrationDate.get_date()
        
        eqType = session.query(EquipmentType).filter_by(name=eqType).one()
        eqUnitPrice = session.query(EquipmentUnit).filter_by(name=eqUnitPrice).one()
        eqLTOStatus = session.query(LTOStatus).filter_by(name=eqLTOStatus).one()
        eqAvailabilityStatus = session.query(EquipmentStatus).filter_by(name=eqAvailabilityStatus).one()
        
        equipment = Equipment(eqNumber, eqMake, eqEngineNumber, eqPlateNumber, 
                              eqChassisNumber, eqRentalRate, eqRegistrationDate, 
                              eqType.id, eqUnitPrice.id, eqLTOStatus.id, 
                              eqAvailabilityStatus.id)
        
        session.add(equipment)
        session.commit()
        
        self.update_eqListstore([equipment])
        
    def inPerformAdd(self):
        
        """
        Performs the actual inventory add. This method updates both GUI 
        and the database.
        """
        
        #self.set_cursor("watch")
        
        unit_name = self.get_combobox_value(self.itemUnitCombobox)
        unit = session.query(Unit).filter_by(name=unit_name).one()
        category_name = self.get_combobox_value(self.itemCategoryCombobox)
        category = session.query(Category).filter_by(name=category_name).one()
        
        ## TODO: change warehouse_id
        item = Item(self.itemNameEntry.get_text(), unit.id, category.id)
        
        # iterate the inStockListstore and get all stocks
        _iter = self.inStockListstore.get_iter_first()
        while _iter is not None:
            
            item.stocks.append(self.inStockListstore.get_value(_iter, 0))
            
            _iter = self.inStockListstore.iter_next(_iter)
            
        session.add(item)
        session.commit()
        
        self.update_inListstore([item])
        
    def cuPerformAdd(self):
        
        """
        Performs the actual customer add. This method updates both GUI 
        and the database.
        """
        
        #self.set_cursor("watch")
        
        gender = {_("Male"):1, _("Female"):2}
        
        gnModel = self.cuGenderCombobox.get_model()
        gnActive = self.cuGenderCombobox.get_active()
        ciModel = self.cuCityCombobox.get_model()
        ciActive = self.cuCityCombobox.get_active()
        saModel = self.cuStateCombobox.get_model()
        saActive = self.cuStateCombobox.get_active()
        coModel = self.cuCountryCombobox.get_model()
        coActive = self.cuCountryCombobox.get_active()
        
        ln = self.cuLastnameEntry.get_text()
        fn = self.cuFirstnameEntry.get_text()
        mn = self.cuMiddlenameEntry.get_text()
        st = self.cuStreetEntry.get_text()
        zi = self.cuZipcodeEntry.get_text()
        cn = PREFIX + self.cuContactnumberEntry.get_text()
        gn = gender[gnModel[gnActive][0]]
        ci = ciModel[ciActive][0]
        sa = saModel[saActive][0]
        co = coModel[coActive][0]
        
        temp_cust = Customer(ln, fn, mn, gn, cn, st, zi)
        temp_cust = insertCustomer(session, temp_cust, ci, sa, co)
        
        self.update_cuListstore([temp_cust])
        
        #self.root_window.set_cursor(None)
        
    def rePerformRental(self, customer):
        
        self.reNotebook.set_current_page(1)
        
        self.reCuCode.set_label("<span foreground='blue'><b>%s</b></span>" % customer.id)
        self.reCuName.set_label("<span foreground='blue'><b>%s</b></span>" % customer.full_name)
        self.reCuAddress.set_label("<span foreground='blue'><b>%s, %s</b></span>" % (customer.street, customer.get_city()))
        self.reCuAddress2.set_label("<span foreground='blue'><b>%s %s   %s</b></span>" % 
            (customer.zip_code, customer.state_city.name, customer.state_city.country.name))
        
    def update_inListstore(self, itemList):
        
        """
        Updates the inventory ListStore.
        """
        
        for instance in itemList:
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.id)
            item.append(instance.name)
            item.append("%s %s" % (instance.getStocks(self.current_permissions['warehouse_access']), instance.unit.name))
            
            self.inListstore.append(item)
            
    def update_exListstore(self, expense):
        
        item = []
        
        item.append(expense)
        item.append(expense.date)
        item.append(expense.po_number)
        item.append(expense.equipment.number)
        item.append("%.2f" % (expense.getAmount(session)))
        
        self.exListstore.append(item)
            
        
    def update_eqListstore(self, equipmentList):
        
        for instance in equipmentList:
            
            equipment = []
            
            equipment.append(instance)
            equipment.append(instance.id)
            equipment.append(instance.number)
            equipment.append(instance.equipment_type.name)
            equipment.append(instance.make)
            equipment.append(instance.engine_number)
            equipment.append(instance.plate_number)
            equipment.append(instance.chassis_number)
            equipment.append(_("%.2f / %s") % (instance.rental_rate, instance.equipment_unit.name))
            equipment.append(instance.lto_status.name)
            equipment.append(instance.equipment_status.name)
            
            self.eqListstore.append(equipment)
            
    def update_cuListstore(self, cuList):
        
        """
        Updates the customer ListStore.
        """
        
        gender = {1:_("(M)"), 2:_("(F)")}
        
        for instance in cuList:
            
            customer = []
            
            customer.append(instance)
            customer.append(instance.id)
            customer.append(instance.id)
            customer.append("%s %s" % (instance.full_name, gender[instance.gender]))
            customer.append(instance.contact_number)
            customer.append(instance.street)
            customer.append(instance.get_city())
            customer.append(instance.state_city.name)
            customer.append(instance.zip_code)
            customer.append(instance.state_city.country.name)
            
            self.cuListstore.append(customer)
            
    def update_reCuListstore(self, cuList):
        
        """
        Updates the rental ListStore.
        """
        
        gender = {1:_("(M)"), 2:_("(F)")}
        
        for instance in cuList:
            
            customer = []
            
            customer.append(instance)
            customer.append(instance.id)
            customer.append(instance.id)
            customer.append("%s %s" % (instance.full_name, gender[instance.gender]))
            customer.append(instance.contact_number)
            customer.append(instance.street)
            customer.append(instance.city.name)
            customer.append(instance.state.name)
            customer.append(instance.zip_code)
            customer.append(instance.country.name)
            
            self.reCuListstore.append(customer)
            
    def populate_reRepairListstore(self, from_date, to_date):
        
        self.reRepairListstore.clear()
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==self.equipment.id, 
            Expense.date >= (from_date), 
            Expense.date <= (to_date))).order_by(Expense.id):
            
            for repair in ex.repairs:
                
                print repair
                
                item = []
                    
                item.append(ex)
                item.append(ex.date)
                item.append(repair.service)
                item.append(repair.scope)
                item.append("%.2f" % repair.labor)
                
                total += repair.labor
                
                self.reRepairListstore.append(item)
                    
        self.reRepairTotalLabel.set_markup_with_mnemonic("<b>Total: %.2f</b>" % total)
        self.reSummaryRepairLabel.set_text("%.2f" % total)
        
    def populate_reSalaryListstore(self, from_date, to_date):
        
        self.reSalaryListstore.clear()
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==self.equipment.id, 
            Expense.date >= (from_date), 
            Expense.date <= (to_date))).order_by(Expense.id):
            
            for salary in ex.salaries:
                
                item = []
                
                op = session.query(Operator).filter(Operator.id==salary.operator_id).one()
                    
                item.append(ex)
                item.append(ex.date)
                item.append("%s, %s" % (op.last_name, op.first_name))
                item.append(salary.remarks)
                item.append("%.2f" % salary.amount)
                
                total += salary.amount
                
                self.reSalaryListstore.append(item)
                    
        self.reSalaryTotalLabel.set_markup_with_mnemonic("<b>Total: %.2f</b>" % total)
        self.reSummarySalaryLabel.set_text("%.2f" % total)
            
    def populate_reReportListstore(self, summary, liststore, label, category_id, from_date, to_date):
        
        liststore.clear()
        
        total = 0
        for ex in session.query(Expense).filter(and_(
            Expense.equipment_id==self.equipment.id, 
            Expense.date >= (from_date), 
            Expense.date <= (to_date))).order_by(Expense.id):
            
            for purchase in ex.purchases:
                
                stock = session.query(Stock).filter(Stock.id==purchase.stock_id).one()
                
                if stock.items[0].category_id==category_id:
                    
                    item = []
                    
                    item.append(ex)
                    item.append(ex.date)
                    item.append(ex.po_number)
                    item.append(stock.items[0].name)
                    item.append(purchase.quantity)
                    item.append(stock.items[0].unit.name)
                    item.append("%.2f" % stock.unit_price)
                    item.append("%.2f" % (purchase.quantity * stock.unit_price))
                    
                    total += purchase.quantity * stock.unit_price
                    liststore.append(item)
                    
        label.set_markup_with_mnemonic("<b>Total: %.2f</b>" % total)
        summary.set_text("%.2f" % total)
        
    def populate_reListstore(self, li=None):
        
        if li == None:
            
            li = session.query(Equipment).order_by(Equipment.id)
        
        self.reListstore.clear()
        for eq in li:
            
            equipment_id = eq.id
            
            total_parts = self.get_total_expense_by_category(equipment_id, 2)
            total_fuel = self.get_total_expense_by_category(equipment_id, 1)
            
            total_repair = self.get_total_repair_expense(equipment_id)
            total_other  = self.get_total_salary_expense(equipment_id)
            total_income = 0
            
            total_expense = total_parts + total_fuel + total_repair + total_other
            
            item = []
            item.append(eq)
            item.append(eq.number)
            item.append(eq.equipment_type.name)
            item.append("%s %.2f" % (PREFIX, total_expense))
            item.append("%s %.2f" % (PREFIX, total_income))
            item.append("%s %.2f" % (PREFIX, total_income - total_expense))
            
            self.reListstore.append(item)
            
    def populate_inListstore(self):
        
        for instance in session.query(Item).filter(Item.category_id.in_(self.current_permissions['category_access'])):
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.id)
            item.append(instance.name)
            item.append("%s %s" % (instance.getStocks(self.current_permissions['warehouse_access']), instance.unit.name))
            
            self.inListstore.append(item)
            
    def update_exItListstore(self, stock, quantity, item_name, unit_name):
        
        item = []
        
        item.append(stock)
        item.append(item_name)
        item.append(quantity)
        item.append(unit_name)
        item.append(stock.unit_price)
        item.append(stock.unit_price * quantity)
        
        self.exItListstore.append(item)
        
        value = float(self.exTotalLabelValue.get_text())
        value = value + (stock.unit_price * quantity)
        self.exTotalLabelValue.set_text(str(value))
        
    def populate_maWarehousesListstore(self):
        
        for instance in session.query(Warehouse):
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.name)
            item.append(instance.description)
            
            self.maWarehousesListstore.append(item)
    
    def populate_maOperatorsListstore(self):
        
        for instance in session.query(Operator):
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.last_name)
            item.append(instance.first_name)
            
            self.maOperatorsListstore.append(item)
    
    def populate_itemUnitListstore(self):
        
        self.itemUnitListstore.append([_("Select one")])
        for instance in session.query(Unit).order_by(Unit.name):
            
            self.itemUnitListstore.append([instance.name])
            
    def populate_maUnitsListstore(self):
        
        for instance in session.query(Unit):
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.name)
            
            self.maUnitsListstore.append(item)
            
    def populate_maUsUserListstore(self):
        
        for instance in session.query(User):
            
            item = []
            
            item.append(instance)
            item.append(instance.id)
            item.append(instance.type)
            item.append(instance.username)
            
            self.maUsUserListstore.append(item)
            
    def populate_eqListstore(self):
        
        for instance in session.query(Equipment).order_by(Equipment.number):
            
            equipment = []
            
            equipment.append(instance)
            equipment.append(instance.id)
            equipment.append(instance.number)
            equipment.append(instance.equipment_type.name)
            equipment.append(instance.make)
            equipment.append(instance.engine_number)
            equipment.append(instance.plate_number)
            equipment.append(instance.chassis_number)
            equipment.append(_("%.2f / %s") % (instance.rental_rate, instance.equipment_unit.name))
            equipment.append(instance.lto_status.name)
            equipment.append(instance.equipment_status.name)
            
            self.eqListstore.append(equipment)
            
    def populate_exUnitListStore(self):
        
        self.exUnitListStore.clear()
        self.exUnitListStore.append([_("Select one")])
        for unit in session.query(Equipment).order_by(Equipment.number):
            
            self.exUnitListStore.append([unit.number])
            
        self.exEqUnitCombobox.set_model(self.exUnitListStore)
        self.exEqUnitCombobox.set_active(0)
        
    def populate_exOperatorListStore(self):
        
        self.exOperatorListStore.clear()
        self.exOperatorListStore.append([_("Select one")])
        for op in session.query(Operator).order_by(Operator.id):
            
            name = "%s, %s" % (op.last_name, op.first_name)
            self.exOperatorListStore.append([name])
            
        self.exExSaOperatorCombobox.set_model(self.exOperatorListStore)
        self.exExSaOperatorCombobox.set_active(0)
            
    def populate_exItemListStore(self):
        
        self.exItemListStore.clear()
        
        self.exItemListStore.append([_("Select one")])
        for item in session.query(Item).order_by(Item.id):
            
            if item.getStocks(self.current_permissions['warehouse_access']):
                
                self.exItemListStore.append([item.name])
                
        self.exItemCombobox.set_model(self.exItemListStore)
        self.exItemCombobox.set_active(0)
            
    def populate_inStockListstore(self, stocks):
        
        self.inStockListstore.clear()
        
        for instance in stocks:
            
            if instance.credit > 0 and instance.warehouse.id in self.current_permissions['warehouse_access']:
            
                stock = []
            
                stock.append(instance)
                stock.append(instance.date)
                stock.append("%s" % instance.credit)
                stock.append("%.2f" % instance.unit_price)
                stock.append(instance.warehouse.name)
                stock.append(instance.description)
                
                self.inStockListstore.append(stock)
                
    def update_inStockListstore(self, stocks):
        
        for instance in stocks:
            
            if instance.credit > 0:
            
                stock = []
            
                stock.append(instance)
                stock.append(instance.date)
                stock.append("%s" % instance.credit)
                stock.append("%s" % instance.unit_price)
                stock.append(instance.warehouse.name)
                stock.append(instance.description)
                
                self.inStockListstore.append(stock)
            
    def populate_cuStateCombobox(self, country_id):
        
        self.cuStateListStore.clear()
        
        self.cuStateListStore.append([_("Select one")])
        
        for state_city in session.query(StateCity).filter(StateCity.country_id==country_id).order_by(StateCity.name):
            
            self.cuStateListStore.append([state_city.name])
            
        self.cuStateCombobox.set_model(self.cuStateListStore)
        self.cuStateCombobox.set_active(0)
        
    def populate_userWarehouseListstore(self):
        
        self.userWarehouseListstore.clear()
        for instance in session.query(Warehouse).order_by(Warehouse.name):
            
            self.userWarehouseListstore.append([instance.name])
            
    def populate_userCategoryListstore(self):
        
        self.userCategoryListstore.clear()
        for instance in session.query(Category).order_by(Category.name):
            
            self.userCategoryListstore.append([instance.name])
            
    def populate_cuCityCombobox(self, state_id):
        
        self.cuCityListStore.clear()
        
        self.cuCityListStore.append([_("Select one")])
        
        state_city = session.query(StateCity).filter(StateCity.id==state_id).one()
        
        for city in state_city.get_cities():
            
            self.cuCityListStore.append([city])
            
        self.cuCityCombobox.set_model(self.cuCityListStore)
        self.cuCityCombobox.set_active(0)
        
    def add_image(self, parent, filename, text):
        
        box = gtk.VBox(False, 0)
        box.set_border_width(2)
        
        image = gtk.Image()
        image.set_from_file(os.path.join(self.local_path, "img", filename))
        
        label = gtk.Label()
        label.set_text_with_mnemonic(text)
        
        box.pack_start(image, False, False, 3)
        box.pack_start(label, False, False, 3)
        
        image.show()
        label.show()
        
        return box
        
    def show_loginDialog(self):
        
        ret_value = -1
        self.current_user = None
        
        self.loginDialog     = self.builder.get_object("loginDialog")
        
        self.loUsernameEntry = self.builder.get_object("loUsernameEntry")
        self.loPasswordEntry = self.builder.get_object("loPasswordEntry")
        
        self.loUsernameLabel = self.builder.get_object("loUsernameLabel")
        self.loPasswordLabel = self.builder.get_object("loPasswordLabel")
        
        self.loWidgets = \
        [
            [self.loUsernameEntry, self.loUsernameLabel, _("_Username:"), True], 
            [self.loPasswordEntry, self.loPasswordLabel, _("_Password:"), True], 
        ]
        
        self.loUsernameEntry.set_activates_default(True)
        self.loPasswordEntry.set_activates_default(True)
        
        result = self.loginDialog.run()
        while result == gtk.RESPONSE_OK and self.validate_widgets(self.loWidgets) == -1:
            
            result = self.loginDialog.run()
            
            self.reset_widgets(self.loWidgets, False)
            
        if (result == gtk.RESPONSE_OK):
            
            username = self.loUsernameEntry.get_text()
            password = self.loPasswordEntry.get_text()
            
            u = User(username, password)
            
            try:
                user = session.query(User).filter(User.username==username).one()
                
                if u.password == user.password:
                    
                    self.current_user = user
                    
                    ret_value = 0
                    
            except NoResultFound:
                
                pass
                
        elif (result == gtk.RESPONSE_CANCEL or result == gtk.RESPONSE_DELETE_EVENT):
            
            ret_value = 1
            
        self.loginDialog.hide()
        
        return ret_value
    
    def set_cursor(self, value):
        
        cursor_dict = {"watch":gtk.gdk.WATCH}
        
        cursor = gtk.gdk.Cursor(cursor_dict[value])
        
        #self.root_window.set_cursor(cursor)
        
    def set_permissions(self):
        
        text = _("Welcome to ") + APP_NAME + " " + __appversion__ + " || " + \
        _("user: ") + self.current_user.username
        
        self.statusbar.push(self.context_id, text)
        
        self.current_permissions = self.current_user.get_permissions()
        
        di = \
        {
            'view_rental':self.reButton, 
            'view_inventory':self.inButton, 'add_inventory':self.inAddButton, 
            'view_equipment':self.trButton, 'add_equipment':self.eqAddButton, 
            'view_report':self.rpButton,
            'view_maintenance':self.maButton,
            'view_expense':self.exButton, 'add_expense':'', 
            'view_user':self.maUsUserModifyButton,
        }
        
        # Viewing and Adding
        for k in di.keys():
            
            if k != 'add_expense':
                
                di[k].set_sensitive(self.current_permissions[k])
                
            else:
                print k
                self.exAddButton.set_sensitive(self.current_permissions[k])
                self.exRepairAddButton.set_sensitive(self.current_permissions[k])
                self.exSalaryAddButton.set_sensitive(self.current_permissions[k])
                
    def security(self):
        
        tries = 3
        
        while tries != 0:
            
            ret_value = self.show_loginDialog()
            
            if ret_value != 0 and ret_value != 1:
                
                tries -= 1
                
            elif ret_value == 1:
                
                sys.exit(0)
                
            else:
                
                break
            
        if ret_value != 0:
            
            sys.exit(1)
            
    def get_moviesByCast(self, regex, movie, movieList):
        
        for cast in movie.casts:
            
            if regex.search(cast.full_name) and movie not in movieList:
                
                movieList += [movie]
                
        return movieList
        
def open_url_in_browser(url):
    """
    Opens a url in the desktop's default browser

    :param url: the url to open
    """
    
    import threading
    import webbrowser
    
    class BrowserThread(threading.Thread):
    
        def __init__(self, url):
        
            threading.Thread.__init__(self)
            self.url = url
            
        def run(self):
        
            webbrowser.open(self.url)
            
    BrowserThread(url).start()
    
if __name__ == "__main__":
    
    inventorius = Inventorius()
    gtk.gdk.threads_init()
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
    
